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
|
|---|---|---|---|---|---|---|
139e6fb8c271c338dbfe39f680afff7b1809579c
|
C#
|
MuhammadFaizanKhan/3DWalker
|
/3DWalker/Assets/3D Walker/Scripts/Camera/WalkCamRotationOnMouse.cs
| 2.9375
| 3
|
using UnityEngine;
namespace ThreeDWalker
{
/// <summary>
/// Function: This script will use to Rotate the Walk Camera using mouse right click
/// Author: Muhammad Faizan Khan
/// </summary>
public class WalkCamRotationOnMouse : MonoBehaviour
{
/// <summary>
/// Head Object in Walk Camera
/// </summary>
GameObject walkCamHead;
/// <summary>
/// Head Object in Walk Camera
/// </summary>
GameObject walkCamBody;
public float rotationSpeed = 500f;
void Start()
{
walkCamBody = this.transform.gameObject;//Get the Walk cam Body
walkCamHead = this.transform.GetChild(0).gameObject;//Get the Walk cam head (child object)
Debug.Log("walk camera" + walkCamHead.name);
}
void Update()
{
if (Input.GetMouseButton(1)) //left click detect and use cam rotation on mouse
{
var mouseX = Input.GetAxis("Mouse X");
walkCamBody.transform.localEulerAngles += new Vector3(0f, mouseX * rotationSpeed * Time.deltaTime, 0f);
var mouseY = Input.GetAxis("Mouse Y");
walkCamHead.transform.localEulerAngles -= new Vector3(mouseY * rotationSpeed * Time.deltaTime, 0f, 0f);
}
}
}
}
|
996290a4adcfd6980028b506c3888a000950db17
|
C#
|
mjeaton/RockLib.Analyzers.Json
|
/RockLib.Analyzers.Json/Syntax/ObjectMemberSyntax.cs
| 2.765625
| 3
|
using System.Collections.Generic;
namespace RockLib.Analyzers.Json
{
public class ObjectMemberSyntax : ContainerSyntaxNode
{
public ObjectMemberSyntax(StringSyntax name, ColonSyntax colon, JsonSyntaxNode value)
: this(name, colon, value, null)
{
}
public ObjectMemberSyntax(StringSyntax name, ColonSyntax colon, JsonSyntaxNode value, CommaSyntax comma)
: base(GetChildren(name, colon, value, comma))
{
Name = name;
Colon = colon;
Value = value;
Comma = comma;
}
public StringSyntax Name { get; }
public ColonSyntax Colon { get; }
public JsonSyntaxNode Value { get; }
public CommaSyntax Comma { get; }
public override bool IsValid =>
Name != null
&& Colon != null
&& Value != null
&& Value.IsValueNode;
public override bool IsValueNode => false;
public ObjectMemberSyntax WithName(StringSyntax name) =>
new ObjectMemberSyntax(name, Colon, Value, Comma);
public ObjectMemberSyntax WithColon(ColonSyntax colon) =>
new ObjectMemberSyntax(Name, colon, Value, Comma);
public ObjectMemberSyntax WithValue(JsonSyntaxNode value) =>
new ObjectMemberSyntax(Name, Colon, value, Comma);
public ObjectMemberSyntax WithComma(CommaSyntax comma) =>
new ObjectMemberSyntax(Name, Colon, Value, comma);
public ObjectMemberSyntax WithoutComma() =>
new ObjectMemberSyntax(Name, Colon, Value, null);
protected override JsonSyntaxNode ReplaceCore(JsonSyntaxNode oldNode, JsonSyntaxNode newNode)
{
if (Value != null)
{
var replacementValue = Value.ReplaceNode(oldNode, newNode);
if (!ReferenceEquals(replacementValue, Value))
return WithValue(replacementValue);
}
if (Name != null)
{
var replacementName = Name.ReplaceNode(oldNode, newNode);
if (!ReferenceEquals(replacementName, Name))
return WithName(replacementName);
}
if (Colon != null)
{
var replacementColon = Colon.ReplaceNode(oldNode, newNode);
if (!ReferenceEquals(replacementColon, Colon))
return WithColon(replacementColon);
}
if (Comma != null)
{
var replacementComma = Comma.ReplaceNode(oldNode, newNode);
if (!ReferenceEquals(replacementComma, Comma))
return WithComma(replacementComma);
}
return this;
}
private static IReadOnlyList<JsonSyntaxNode> GetChildren(StringSyntax name,
ColonSyntax colon, JsonSyntaxNode value, CommaSyntax comma)
{
var list = new List<JsonSyntaxNode>();
if (name != null)
list.Add(name);
if (colon != null)
list.Add(colon);
if (value != null)
list.Add(value);
if (comma != null)
list.Add(comma);
return list;
}
}
}
|
e35a22d042008f6ebdb0fb7f3e1e76be383a07ab
|
C#
|
Weyne23/Academia
|
/CFB_Academia/F_NovoUsuario.cs
| 2.625
| 3
|
using CFB_Academia.Models;
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 CFB_Academia
{
public partial class F_NovoUsuario : Form
{
public F_NovoUsuario()
{
InitializeComponent();
}
private void limparCampos()
{
tb_nome.Clear();
tb_senha.Clear();
tb_userName.Clear();
n_nivel.Value = 1;
cb_status.Text = "";
tb_nome.Focus();
}
private void btn_fechar_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_cancelar_Click(object sender, EventArgs e)
{
this.Close();
}
private void btn_novo_Click(object sender, EventArgs e)
{
limparCampos();
}
private void btn_salvar_Click(object sender, EventArgs e)
{
using (var ctx = new AcademiaContexto())
{
Usuario usuario = new Usuario();
usuario.NomeUsuario = tb_nome.Text;
usuario.NivelUsuario = Convert.ToInt32(Math.Round(n_nivel.Value, 0));//Tirando as casas decimais
usuario.StatusUsuario = cb_status.Text;
usuario.UserName = tb_userName.Text;
usuario.SenhaUsuario = tb_senha.Text;
var user = ctx.Usuarios.SingleOrDefault(u => u.UserName == tb_userName.Text);
if(user == null)
{
ctx.Add(usuario);
ctx.SaveChanges();
MessageBox.Show("Usuario Cadastrado com sucesso.", "Mensagem");
limparCampos();
}
else
{
MessageBox.Show("Usuário já Cadastrado!", "Erro");
}
}
}
}
}
|
e881d1061a80ca7a5257889ae26536a6567f3f2d
|
C#
|
Rawenvoys/NorseWar-PZ-
|
/Gra/NorseWar/Helper/SearchUser.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NorseWar.Models;
using NorseWar.Models.DAL;
using NorseWar.Helper;
namespace NorseWar.Helper
{
public class SearchUser
{
public string Text { get; set; }
public static Account Search(SearchUser searchuser)
{
GameContext db = new GameContext();
Account user = new Account();
List<string> listOfString = new List<string>() { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
int length = searchuser.Text.Length;
string[] tab = new string[length];
string position = null;
int pos = 0;
for (int i = 0; i < length; i++)
tab[i] = searchuser.Text[i].ToString();
for (int i = 0; i < length; i++)
{
if (listOfString.Contains(tab[i]))
position += tab[i];
else
{
position = null;
break;
}
}
if(position != null)
{
pos = Int32.Parse(position);
user = Methods.ShowUserFromPosition(pos);
}
Account account = db.Accounts.SingleOrDefault(u => u.Login == searchuser.Text || u.AccountID == user.AccountID);
return account;
}
}
}
|
4c4a458dcc24896d28387669d08995890813392f
|
C#
|
Sleepdot/PharmacyGame
|
/Assets/Scripts/Level Scripts/Level 1 (Skin)/Level1Phase3.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Level1Phase3 : Phase
{
public GameObject itchingEnemy;
public GameObject painEnemy;
public GameObject anaphylaxisEnemy;
//Initialize populates the data for the enemies and waves
public override void Initialize()
{
base.Initialize();
//Enemies for different waves
//itching
DataManager.WaveEnemy w1Itching = new DataManager.WaveEnemy(itchingEnemy, 1f, 5);
DataManager.WaveEnemy w2Itching = new DataManager.WaveEnemy(itchingEnemy, 1f, 10);
DataManager.WaveEnemy w3Itching = new DataManager.WaveEnemy(itchingEnemy, 1f, 15);
//pain
DataManager.WaveEnemy w1Pain = new DataManager.WaveEnemy(painEnemy, 2f, 5);
DataManager.WaveEnemy w2Pain = new DataManager.WaveEnemy(painEnemy, 2f, 10);
//anaphylaxis
DataManager.WaveEnemy w1Anaphylaxis = new DataManager.WaveEnemy(anaphylaxisEnemy, 3f, 5);
//wave1
DataManager.Wave w1 = new DataManager.Wave();
DataManager.WaveEnemy[] w1Enemies = {w1Itching};
w1.enemies = w1Enemies;
//wave2
DataManager.Wave w2 = new DataManager.Wave();
DataManager.WaveEnemy[] w2Enemies = {w1Itching, w1Pain};
w2.enemies = w2Enemies;
//wave3
DataManager.Wave w3 = new DataManager.Wave();
DataManager.WaveEnemy[] w3Enemies = {w1Itching, w1Pain, w1Anaphylaxis};
w3.enemies = w3Enemies;
DataManager.Wave[] newWaves = {w1, w2, w3};
waves = newWaves;
waveDescriptions = new string[]{
"Itching: x5", //first wave
"Itching: x10\nPain: x5", //Second wave
"Itching: x15\nPain: x10\nAnaphylaxis: x5" //Third Wave
};
}
void Awake(){
Initialize();
}
// Start is called before the first frame update
protected override void Start()
{
base.Start();
}
// Update is called once per frame
protected override void Update()
{
base.Update();
}
}
|
f75893738af56b0c3bf3a2ae2e143b69d905c4fb
|
C#
|
a4099181/Challenges
|
/Challenges/Challenges/Arrays/SwapBlocksParallel.cs
| 3.15625
| 3
|
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace Challenges.Challenges.Arrays
{
class SwapBlocksParallel
{
internal static string Swap( string input, int firstBlockSize )
=> new string( Swap( input.ToCharArray(), firstBlockSize ) );
internal static char[] Swap( char[] input, int firstBlockSize )
{
if (2 * firstBlockSize > input.Length)
{
MoveToLeft( input, 0, input.Length, input.Length - firstBlockSize );
}
else
{
MoveToRight( input, 0, input.Length, firstBlockSize );
}
return input;
}
static void MoveToRight( char[] input, int from, int to, int size )
{
var freeBlockSize = ( to - from ) % size;
var range = new
{
from = from + size,
to = to - freeBlockSize
};
Parallel.For( 0, size, j => MoveToRight( input, range.@from, range.to, j, size ) );
if (freeBlockSize > 0)
{
MoveToLeft( input, range.to - size, to, freeBlockSize );
}
}
static void MoveToRight( char[] input, int from, int to, int offset, int size )
{
Debug.WriteLine( $"{Thread.CurrentThread.ManagedThreadId}==> to right ==> [>>>xxxx]" );
for ( var i = from; i < to; i = i + size )
{
SwapWithPrevious( input, i + offset, size );
}
}
static void MoveToLeft( char[] input, int from, int to, int size )
{
var freeBlockSize = ( to - from ) % size;
var range = new
{
from = from + freeBlockSize,
to = to - size
};
Parallel.For( 0, size, j => MoveToLeft( input, range.@from, range.to, j, size ) );
if (freeBlockSize > 0)
{
MoveToRight( input, from, range.from + size, freeBlockSize );
}
}
static void MoveToLeft( char[] input, int @from, int to, int offset, int size )
{
Debug.WriteLine( $"{Thread.CurrentThread.ManagedThreadId}<== to left <== [xxxx<<<]" );
for ( var i = to; i > from; i = i - size )
{
SwapWithPrevious( input, i + offset, size );
}
}
static unsafe void SwapWithPrevious( char[] input, int start, int size )
{
fixed ( char* swap = &input[ start ]
, with = &input[ start - size ] )
{
var swapped = *swap;
*swap = *with;
*with = swapped;
}
Debug.WriteLine( $"{Thread.CurrentThread.ManagedThreadId}){new string( input ),15}" );
}
}
}
|
4f0d19088d3d04db4b5f88afbe94bedc4f592270
|
C#
|
Grimelios/LudumDare41
|
/LudumDare41/Structures/SafeList.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LudumDare41.Structures
{
public class SafeList<T>
{
private List<T> mainList;
private List<T> addList;
private List<T> removeList;
public SafeList()
{
mainList = new List<T>();
addList = new List<T>();
removeList = new List<T>();
}
public IEnumerable<T> MainList => mainList;
public void Add(T item)
{
addList.Add(item);
}
public void Add(T[] items)
{
addList.AddRange(items);
}
public void Add(List<T> items)
{
addList.AddRange(items);
}
public void Remove(T item)
{
removeList.Add(item);
}
public void Remove(T[] items)
{
removeList.AddRange(items);
}
public void Remove(List<T> items)
{
removeList.AddRange(items);
}
public void ProcessChanges()
{
}
}
}
|
c28a6779bb7f6a5a324e9f7dde2d55517912a721
|
C#
|
Ash2022/MemGame
|
/Assets/Scripts/MemGame/models/ModelManager.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using UnityEngine;
namespace MemGame.models
{
public class ModelManager :MonoBehaviour
{
Table m_table;
List<BotMemory> m_bots = new List<BotMemory>();
public enum BotLevel
{
Geniuos,
smart,
medium,
lame,
retard
}
static ModelManager m_instance;
public static ModelManager Instance {
get {
if (m_instance == null) {
ModelManager manager = GameObject.FindObjectOfType<ModelManager> ();
m_instance = manager.GetComponent<ModelManager> ();
}
return m_instance;
}
}
public ModelManager ()
{
}
public void Init()
{
GenerateBots ();
}
private void GenerateBots()
{
m_bots.Add (new BotMemory (100, 0,70)); // never forget
m_bots.Add (new BotMemory (90, 1,70));
m_bots.Add (new BotMemory (70, 2,70));
m_bots.Add (new BotMemory (60, 2,70));
m_bots.Add (new BotMemory (50, 3,70)); // never remember
}
public Table Table {
get {
return m_table;
}
set {
m_table = value;
}
}
public List<BotMemory> Bots {
get {
return m_bots;
}
}
}
}
|
e849697c0f25309b8b8275ca306cf3f1084a04b2
|
C#
|
ChenQianPing/Tdf.CSharpDay
|
/Tdf.CSharpDay/Chapter1/TestEncrypter.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Tdf.CSharpDay.Chapter1
{
public class TestEncrypter
{
public static void TestMethod1()
{
string input = "abc";
input = "银行密码统统都给我";
string key = "justdoit";
string result = string.Empty;
// MD5加密结果:ee1124a603a7d6b5a8b352cf9635234d
result = Encrypter.EncryptByMd5(input);
Console.WriteLine("MD5加密结果:{0}", result);
// SHA1加密结果:85-9D-97-0F-55-E7-A0-4C-60-CE-37-BE-0D-51-F0-F1-23-DD-C5-52
result = Encrypter.EncryptBySha1(input);
Console.WriteLine("SHA1加密结果:{0}", result);
// DES加密结果:64-22-8B-65-BB-C3-15-E1-87-C7-28-A8-C5-75-CF-80-12-A3-57-A7-E8-2D-FC - 81 - 1A - 2C - 5F - 86 - 0A - 4A - 6E-37
result = Encrypter.EncryptString(input, key);
Console.WriteLine("DES加密结果:{0}", result);
result = Encrypter.DecryptString(result, key);
Console.WriteLine("DES解密结果:{0}", result);
// DES加密结果:ZCKLZbvDFeGHxyioxXXPgBKjV6foLfyBGixfhgpKbjc=
result = Encrypter.EncryptByDes(input, key);
Console.WriteLine("DES加密结果:{0}", result);
result = Encrypter.DecryptByDes(result, key);
Console.WriteLine("DES解密结果:{0}", result); //结果:"银行密码统统都给我�\nJn7",与明文不一致,为什么呢?在加密后,通过base64编码转为字符串,可能是这个问题。
key = "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
// AES加密结果:AB-60-0A-59-FA-02-19-32-81-2839-6A-75-A4-8C-E5-3D-3B-2A-A4-3A-F7-53 - 7E-17 - A9 - 5F - 35 - 68 - 88 - 84 - 9D
result = Encrypter.EncryptByAes(input, key);
Console.WriteLine("AES加密结果:{0}", result);
result = Encrypter.DecryptByAes(result, key);
Console.WriteLine("AES解密结果:{0}", result);
KeyValuePair<string, string> keyPair = Encrypter.CreateRsaKey();
var privateKey = keyPair.Value;
var publicKey = keyPair.Key;
/*
* 应该是公钥加密,私钥解密的说
* RSA私钥加密后的结果:P1403dWvJczLwUjP3ubkzgxLVdW/GE4YqC2oys5j6fXRagNBMxRcKm5Iz1/
kg2AkewVMBBLpP91g3AbSNE4agykr3hS6PKhc+o9ZdJIKiVOZtZchkotETAtSzkTLxw7LL30tLgqe5pE
zA5QrXkQf4+fv/htwSrKZr3o17GCxUzE=
*/
result = Encrypter.EncryptByRsa(input, publicKey);
Console.WriteLine("RSA私钥加密后的结果:{0}", result);
result = Encrypter.DecryptByRsa(result, privateKey);
Console.WriteLine("RSA公钥解密后的结果:{0}", result);
// 密钥加密,公钥解密
result = Encrypter.EncryptByRsa(input, privateKey);
Console.WriteLine("RSA私钥加密后的结果:{0}", result);
/*
* RSA算法指出私钥加密的信息,只有公钥可以解密。
* 这就给我们实际编程过程中造成了误解,认为可以使用私钥加密,公钥解密。
* 然而,加密时不出错,而解密时会收到“不正确的项”的错误。
*/
// result = Encrypter.DecryptByRsa(result, publicKey);
// Console.WriteLine("RSA公钥解密后的结果:{0}", result);
/*
* 数字签名:WLuHd9/k7NrngvN+wcNMjpdSY/6RKk2Pmk8YnFXM187gNa9Rxy7Y43i7babch/tf3wkX0FT
2y75RC0OTNPEjcQF2ETgk/Nl7zoICRM5xn874gQQy9MdfO/4BAuiEQrgD03bvf2MosXfx49/Jg0oacna
9LKjRGMjnyQXr8sVgzuE=
*/
TestSign();
Console.WriteLine("输入任意键退出!");
Console.ReadKey();
}
/// <summary>
/// 测试数字签名
/// </summary>
public static void TestSign()
{
var originalData = "文章不错,这是我的签名:奥巴马!";
Console.WriteLine($"签名数为:{originalData}");
var keyPair = Encrypter.CreateRsaKey();
var privateKey = keyPair.Value;
var publicKey = keyPair.Key;
// 1、生成签名,通过摘要算法
var signedData = Encrypter.HashAndSignString(originalData, privateKey);
Console.WriteLine($"数字签名:{signedData}");
// 2、验证签名
var verify = Encrypter.VerifySigned(originalData, signedData, publicKey);
Console.WriteLine($"签名验证结果:{verify}");
}
}
}
|
eb220f7ee068506b6f54b78544cc602d99817a14
|
C#
|
DErobin/SE-Opdracht
|
/IO/App_Code/User.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for User
/// </summary>
public class User
{
private string aco; //Date the account was created on in string format
private string lio; //Last date the user logged in in string format
private string rlevel; //Rights of the user in string format
public int Id { get; set; } //ID of the user
public string Username { get; set; } //Username of the user
public string Email { get; set; } //Emailadres of the user
public string Password {get; set;} //Users password
public int Age {get; set;} //Users age
public string AccountCreatedOn {get; set;} //Date the account was created on in string format
public string LastLogin {get; set;} //Date the account was last logged in
public int ProfilePrivacy {get; set;} //The level of profileprivacy the user has set
public int MessagePrivacy {get; set;} //The level of message privacy the user has set
public int MassMessagePrivacy {get; set;} //The level of massmessage privacy the user has set
public int Level {get; set;} //The level of the user
public string Rightslevel {get; set;} //The rights of a user in string format
public User(int id, string username, string email, string password, int age, string aco, string lio,
int ppriv, int mpriv, int mmpriv, int level, string rlevel)
{
Id = id;
Username = username;
Email = email;
Password = password;
Age = age;
AccountCreatedOn = aco;
LastLogin = lio;
ProfilePrivacy = ppriv;
MessagePrivacy = mpriv;
MassMessagePrivacy = mmpriv;
Level = level;
Rightslevel = rlevel;
}
public User(int id, string username, string email, int age, string aco, string lio, int level, string rlevel)
{
this.Id = id;
this.Username = username;
this.Email = email;
this.Age = age;
this.AccountCreatedOn = aco;
this.LastLogin = lio;
this.Level = level;
this.Rightslevel = rlevel;
}
public User(User user)
{
this.Id = user.Id;
this.Username = user.Username;
this.Email = user.Email;
this.Age = user.Age;
this.AccountCreatedOn = user.AccountCreatedOn;
this.LastLogin = user.LastLogin;
this.Level = user.Level;
this.Rightslevel = user.Rightslevel;
}
}
|
92d309a90faea98a6fd54c4b2100979070a6d896
|
C#
|
shi1252/AGEPAstarAlgorithm
|
/Assets/Scripts/Pathfinding.cs
| 2.796875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Diagnostics;
public class Pathfinding : MonoBehaviour {
public Transform seeker, target;
Grid grid;
void Start ()
{
grid = GetComponent<Grid> ();
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
FindPath(seeker.position, target.position);
FindPath2(seeker.position, target.position);
}
}
void FindPath(Vector3 startPos, Vector3 targetPos)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Node startNode = grid.NodeFromWorldPosition(startPos);
Node targetNode = grid.NodeFromWorldPosition(targetPos);
List<Node> openSet = new List<Node> ();
HashSet<Node> closedSet = new HashSet<Node>();
openSet.Add (startNode);
while (openSet.Count > 0) {
// OpenSet에서 가장 낮은 fCost를 가지는 노드를 가져온다.
// 만일 fCost가 동일할 경우 gCost가 적은 쪽을 택함.
Node currentNode = openSet[0];
/* 해당 코드를 작성할 것 */
for (int i = 1; i < openSet.Count; i++)
{
if (currentNode.fCost > openSet[i].fCost)
currentNode = openSet[i];
else if (currentNode.fCost == openSet[i].fCost)
{
if (currentNode.gCost > openSet[i].gCost)
currentNode = openSet[i];
}
}
// 찾은 노드가 최종 노드면 루프 종료
if (currentNode == targetNode)
{
RetracePath(startNode, targetNode);
sw.Stop();
print("List Elapsed Time : " + sw.ElapsedTicks + "Ticks");
return;
}
// 해당 노드를 ClosedSet으로 이동
/* 해당 코드를 작성할 것 */
closedSet.Add(currentNode);
openSet.Remove(currentNode);
// 현재 노드의 이웃들을 모두 가져와 비교
foreach (Node n in grid.GetNeighbours(currentNode))
{
// 이웃 노드가 이미 ClosedSet에 있거나 걸어다니지 못하는 곳이면 제외한다.
/* 해당 코드를 작성할 것 */
if (closedSet.Contains(n) || !n.walkable)
continue;
// 현재 노드를 기점에서 파생된 이웃 노드의 fCost를 계산한다.
/* 해당 코드를 작성할 것 */
int gCost = currentNode.gCost + GetDistance(currentNode, n);
int hCost = GetDistance(n, targetNode);
// 오픈셋에 현재 노드가 없으면 노드에 점수를 설정한 후 추가한다.
if (!openSet.Contains(n))
{
/* 해당 코드를 작성할 것 */
n.gCost = currentNode.gCost + GetDistance(currentNode, n);
n.hCost = GetDistance(n, targetNode);
n.parent = currentNode;
openSet.Add(n);
}
else
{
// 오픈셋에 현재 노드가 이미 있으면 수치를 비교한 후 경로를 교체한다. 동일하면 g수치가 큰 쪽으로 교체한다.
/* 해당 코드를 작성할 것 */
if (n.fCost > gCost + hCost || (n.fCost == gCost + hCost && n.gCost > gCost))
{
n.gCost = gCost;
n.hCost = hCost;
n.parent = currentNode;
}
}
}
}
}
void FindPath2(Vector3 startPos, Vector3 targetPos)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Node startNode = grid.NodeFromWorldPosition(startPos);
Node targetNode = grid.NodeFromWorldPosition(targetPos);
PriorityQueue openSet = new PriorityQueue(grid.Size);
HashSet<Node> closedSet = new HashSet<Node>();
openSet.Enqueue(startNode);
while (openSet.Count > 0)
{
Node currentNode = openSet.Dequeue();
if (currentNode == targetNode)
{
RetracePath(startNode, targetNode);
sw.Stop();
print("PriorityQueue Elapsed Time : " + sw.ElapsedTicks + "Ticks");
return;
}
closedSet.Add(currentNode);
foreach (Node n in grid.GetNeighbours(currentNode))
{
if (closedSet.Contains(n) || !n.walkable)
continue;
int gCost = currentNode.gCost + GetDistance(currentNode, n);
int hCost = GetDistance(n, targetNode);
if (!openSet.Contains(n))
{
n.gCost = currentNode.gCost + GetDistance(currentNode, n);
n.hCost = GetDistance(n, targetNode);
n.parent = currentNode;
openSet.Enqueue(n);
}
else
{
if (n.fCost > gCost + hCost || (n.fCost == gCost + hCost && n.gCost > gCost))
{
n.gCost = gCost;
n.hCost = hCost;
n.parent = currentNode;
}
}
}
}
}
// 경로를 보여준다.
void RetracePath(Node startNode, Node endNode)
{
List<Node> path = new List<Node> ();
Node currentNode = endNode;
while (currentNode != startNode) {
path.Add (currentNode);
currentNode = currentNode.parent;
}
grid.path = path;
}
int GetDistance(Node nodeA, Node nodeB)
{
int dstX = Mathf.Abs(nodeA.gridX - nodeB.gridX);
int dstY = Mathf.Abs(nodeA.gridY - nodeB.gridY);
if(dstX > dstY)
{
return 14*dstY + 10*(dstX - dstY);
}
return 14*dstX + 10*(dstY - dstX);
}
}
|
dd47bdb59103a780c47cd2988a7c8515063b0d39
|
C#
|
bf1024/GetIItemCQRS
|
/GetItemCQRS/Repositories/ItemQueriesRepository.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GetItemCQRS.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
namespace GetItemCQRS.Repositories
{
public interface IItemQueriesRepository
{
string GetNameByID(string guid);
}
public class ItemQueriesRepository : IItemQueriesRepository
{
private readonly IMemoryCache _memoryCache;
public ItemQueriesRepository(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public string GetNameByID(string guid)
{
string name = "";
if(!_memoryCache.TryGetValue(guid, out name))
throw new KeyNotFoundException();
return name;
}
}
}
|
dd4f4c171caac2508866bd6a5cb249a69fe8c67c
|
C#
|
DrakeMorrison/ClassExercise
|
/LegoMinifigures/Torsos/Reptilian.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LegoMinifigures.Torsos
{
class ReptilianTorso : Torso
{
public string ScaleShape { get; set; }
public void Dance()
{
Console.WriteLine($"*Breakdances vigorously in {Color}*");
}
public void Twist()
{
Console.WriteLine("A little bit louder now.");
}
}
}
|
8d770ac340a0181fb71946a5df4131ec189489d7
|
C#
|
yordanov03/Soft-Uni
|
/Soft-Uni/ASP.NET Core/Bus Tickets System/BusTicketSystem.Services/BusCompanyService.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using BusTicketsSystem.Models;
using BusTicketsSystem.Services.Interfaces;
using BusTicketsSystem.Data;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace BusTicketsSystem.Services
{
public class BusCompanyService : IBusCompanyService
{
private readonly BusTicketSystemContext context;
public BusCompanyService(BusTicketSystemContext context)
{
this.context = context;
}
public BusCompany GetBusCompanyById(int busCompanyid)
{
var busCompany = context.BusCompanies.First(c => c.BusCompanyId == busCompanyid);
return busCompany;
}
public BusCompany GetBusCompanyByName(string busCompanyName)
{
var busCompany = context.BusCompanies.First(c => c.BusCompanyName == busCompanyName);
return busCompany;
}
}
}
|
998ad09f7bc6ff17c507faec4e9202410ec9ee2e
|
C#
|
MartinKraemer85/Schach
|
/Schach/Figur/Pferd.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Schach
{
public class Pferd : Figur
{
public Pferd(Farbe farbe, string aktuellePosition, string bildName, Dictionary<string, Figur> dctFigur) : base(farbe, aktuellePosition, bildName, dctFigur)
{
}
public override Bitmap FigurBild
{
get { return this.figurBild; }
}
// 1-8 --> 49-56
// a-h --> 61-68
// Ueberdenken ob dort die abfragen reinkommen ob das Zielfeld ein gleichfarbiges ding hat
// usw.
// reihe --> y
// spalte --> x
public override List<String> listMoeglicheFelder()
{
listMoeglicheZuege = new List<string>();
// Die verschiedenen Zuege des Pferdes:
bool reihePlusZwei = (this.reiheEinsBisAchtValide(2, '8', GroesserKleiner.Kleiner) );
bool reiheMinusZwei = (this.reiheEinsBisAchtValide(-2, '1', GroesserKleiner.Groesser));
bool spaltePlusZwei = (this.spalteAbisHvalide(2, 'h', GroesserKleiner.Kleiner) );
bool spalteMinusZwei = (this.spalteAbisHvalide(-2, 'a', GroesserKleiner.Groesser) );
bool reihePlusEins = (this.reiheEinsBisAchtValide(1, '8', GroesserKleiner.Kleiner));
bool reiheMinusEins = (this.reiheEinsBisAchtValide(-1, '1', GroesserKleiner.Groesser));
bool spaltePlusEins = (this.spalteAbisHvalide(1, 'h', GroesserKleiner.Kleiner) );
bool spalteMinusEins = (this.spalteAbisHvalide(-1, 'a', GroesserKleiner.Groesser));
// zwei rechts, eins nach oben
if ((spaltePlusZwei && reihePlusEins) && !figurImWegEigeneFarbe(this.feldName(2, 1)))
{
listMoeglicheZuege.Add(this.feldName(2, 1));
}
// zwei rects, eins nach unten
if ((spaltePlusZwei && reiheMinusEins) && !figurImWegEigeneFarbe(this.feldName(2, -1)))
{
listMoeglicheZuege.Add(this.feldName(2, -1));
}
// zwei links, eins nach oben
if ((spalteMinusZwei && reihePlusEins) && !figurImWegEigeneFarbe(this.feldName(-2, 1)))
{
listMoeglicheZuege.Add(this.feldName(-2, 1));
}
// zwei links, eins nach unten
if ((spalteMinusZwei && reiheMinusEins) && !figurImWegEigeneFarbe(this.feldName(-2, -1)))
{
listMoeglicheZuege.Add(this.feldName(-2, -1));
}
// zwei hoch, eins nach rechts
if ((spaltePlusEins && reihePlusZwei) && !figurImWegEigeneFarbe(this.feldName(1, 2)))
{
listMoeglicheZuege.Add(this.feldName(1, 2));
}
// zwei hoch, eins nach links
if ((spalteMinusEins && reihePlusZwei) && !figurImWegEigeneFarbe(this.feldName(-1, 2)))
{
listMoeglicheZuege.Add(this.feldName(-1, 2));
}
// zwei runter, eins nach rechts
if ((spaltePlusEins && reiheMinusZwei) && !figurImWegEigeneFarbe(this.feldName(1, -2)))
{
listMoeglicheZuege.Add(this.feldName(1, -2));
}
// zwei runter, eins nach links
if ((spalteMinusEins && reiheMinusZwei) && !figurImWegEigeneFarbe(this.feldName(-1, -2)))
{
listMoeglicheZuege.Add(this.feldName(-1, -2));
}
return listMoeglicheZuege;
}
}
}
|
3a2ff08be4028c81172f3975acab10256b4997d7
|
C#
|
shendongnian/download4
|
/first_version_download2/613875-60444685-215907292-4.cs
| 2.828125
| 3
|
public class WorkerService
{
private readonly IContainer _container = null;
public WorkerService(IContainer container)
{
_container = container ?? throw new ArgumentNullException("container");
}
private IDataContextFactory _contextFactory = null;
public IDataContextFactory ContextFactory
{
get { return _contextFactory ?? (_contextFactory = _container.Resolve<IDataContextFactory>()); }
set { _contextFactory = value; }
}
public void Execute()
{
using(var context = ContextFactory.Create()) // returns a DataContext.
{
// do stuff.
}
}
}
|
7ffc927bff4cea7c8aacf5ed727ec52a93e105ae
|
C#
|
chandum2/Emby.Theater
|
/MediaBrowser.Theater.Interfaces/Commands/ICommandManager.cs
| 2.640625
| 3
|
using System;
using System.Windows;
namespace MediaBrowser.Theater.Interfaces.Commands
{
// Inheriet of routedEventArgs, but for now treat as plan event arges
// Later implement our own routing, notr based on UI tree, to manage Handled
public class CommandEventArgs : EventArgs //.. RoutedEventArgs
{
public Command Command;
public Object Args; // page name, Key, list of widgetsg
public Boolean Handled;
}
public delegate void CommandEventHandler(object sender, CommandEventArgs commandEventArgs);
public interface ICommandManager
{
/// <summary>
/// subscribe to commands. It up to teh subscribe to decide how to exeute teh command.
/// if the subscribe executes the command they should set handed to true
/// </summary>
event CommandEventHandler CommandReceived;
/// <summary>
/// Send a command to command subsribers
/// </summary>
/// <param name="command">The command to send</param>
/// <param name="args">The command arguments</param>
bool ExecuteCommand(Command command, Object args);
}
}
|
014d6bec689b6cdc2bb7a1b4c7b94942a1087914
|
C#
|
henrydem/yongfa365doc
|
/CSharp/Reports/AboutReport/DBMaker.cs
| 2.640625
| 3
|
using System;
using System.Data;
class DBMaker
{
public static DataTable 学生成绩表()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("姓名", typeof(string)));
dt.Columns.Add(new DataColumn("课程", typeof(string)));
dt.Columns.Add(new DataColumn("成绩", typeof(decimal)));
dt.Rows.Add("张三", "语文", 80);
dt.Rows.Add("张三", "数学", 60);
dt.Rows.Add("张三", "化学", 30);
dt.Rows.Add("李四", "语文", 40);
dt.Rows.Add("李四", "数学", 50);
dt.Rows.Add("李四", "化学", 60);
dt.Rows.Add("王五", "语文", 70);
dt.Rows.Add("王五", "数学", 90);
dt.Rows.Add("王五", "化学", 20);
return dt;
}
public static DataTable 文章表()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)));
dt.Columns.Add(new DataColumn("ArticleType", typeof(string)));
dt.Columns.Add(new DataColumn("txtTitle", typeof(string)));
dt.Columns.Add(new DataColumn("AddTime", typeof(DateTime)));
dt.Columns.Add(new DataColumn("UserName", typeof(string)));
for (int i = 0; i < 2000; i++)
{
dt.Rows.Add(i, "[中心文件]", "标题" + i.ToString().PadRight(50, '='), DateTime.Now.Date.AddHours(i), "柳永法" + i);
}
return dt;
}
public static DataTable 班级表()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("班级名称", typeof(string)));
dt.Columns.Add(new DataColumn("几年级", typeof(string)));
dt.Rows.Add("一班", "一年级");
dt.Rows.Add("二班", "一年级");
dt.Rows.Add("三班", "一年级");
return dt;
}
public static DataTable 学生表()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("姓名", typeof(string)));
dt.Columns.Add(new DataColumn("年龄", typeof(string)));
dt.Columns.Add(new DataColumn("性别", typeof(string)));
dt.Columns.Add(new DataColumn("班级名称", typeof(string)));
for (int i = 0; i < 10; i++)
{
dt.Rows.Add("柳永法" + i, i.ToString(), "男", "一班");
}
for (int i = 0; i < 10; i++)
{
dt.Rows.Add("王磊" + i, i.ToString(), "男", "二班");
}
for (int i = 0; i < 10; i++)
{
dt.Rows.Add("曾建新" + i, i.ToString(), "男", "三班");
}
return dt;
}
public static DataTable 人员表()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("姓名", typeof(string)));
dt.Columns.Add(new DataColumn("所在部门", typeof(string)));
dt.Columns.Add(new DataColumn("工资", typeof(decimal)));
dt.Columns.Add(new DataColumn("行号", typeof(int)));
dt.Columns.Add(new DataColumn("列号", typeof(int)));
for (int i = 0; i < 1000; i++)
{
for (int j = 0; j < 5; j++)
{
dt.Rows.Add("柳永法" + i,"技术部", i,i,j);
}
}
return dt;
}
}
|
ea890baa1c178b0505e1acda3b196a383d8d686f
|
C#
|
yukiya7/unity-domino
|
/Domino/Assets/Scripts/DominoGeneraterControl.cs
| 2.546875
| 3
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DominoGeneraterControl : MonoBehaviour {
private GameObject game_camera;
private Vector3[] positions;
private int position_num = 0;
public enum STEP
{
NONE = -1,
IDLE = 0, // 待機中.
DRAWING, // ラインを描いている中(ドラッグ中).
DRAWED, // ラインを描き終わった.
CREATED, // 道路のモデルが生成された.
NUM,
};
public STEP step = STEP.NONE;
public STEP next_step = STEP.NONE;
//線分の最大値
private static int POSITION_NUM_MAX = 100;
private DominoBuilder domino_builder;
private GameObject push_domino;
private Button push_button;
void Start()
{
game_camera = GameObject.FindGameObjectWithTag("MainCamera");
//LineRenderer の線分の数を 0 にしている。
this.GetComponent<LineRenderer>().SetVertexCount(0);
this.positions = new Vector3[POSITION_NUM_MAX];
domino_builder = GameObject.Find("DominoBuilder").GetComponent<DominoBuilder>();
push_button = GameObject.Find("PushButton").GetComponent<Button>();
}
// Update is called once per frame
void Update()
{
// 状態遷移チェック.
switch (this.step)
{
case STEP.NONE:
{
this.next_step = STEP.IDLE;
}
break;
case STEP.IDLE:
{
if (Input.GetMouseButton(0))
{
this.next_step = STEP.DRAWING;
}
}
break;
case STEP.DRAWING:
{
if (!Input.GetMouseButton(0))
{
if (this.position_num >= 2)
{
this.next_step = STEP.DRAWED;
}
else
{
this.next_step = STEP.IDLE;
}
}
}
break;
case STEP.DRAWED:
{
push_button.interactable = true;
}
break;
}
// 状態が遷移したときの初期化.
if (this.next_step != STEP.NONE)
{
switch (this.next_step)
{
case STEP.IDLE:
{
// 前回作成したものを削除しておく.
this.position_num = 0;
this.GetComponent<LineRenderer>().SetVertexCount(0);
domino_builder.RemoveDominos();
}
break;
case STEP.CREATED:
{
//CreateButton を押すとここに来る
Debug.Log("CREATED.");
domino_builder.positions = this.positions;
domino_builder.position_num = this.position_num;
push_domino = domino_builder.createDomino();
}
break;
}
this.step = this.next_step;
this.next_step = STEP.NONE;
}
// 各状態での処理.
switch (this.step)
{
case STEP.DRAWING:
{
Vector3 position = this.unproject_mouse_position();
// 頂点をラインに追加するか、チェックする.
bool is_append_position = false;
if (this.position_num == 0)
{
// 最初のいっこは無条件に追加.
is_append_position = true;
}
else if (this.position_num >= POSITION_NUM_MAX)
{
// 最大個数をオーバーした時は追加できない.
is_append_position = false;
}
else
{
// 直前に追加した頂点から一定距離離れたら追加.
if (Vector3.Distance(this.positions[this.position_num - 1], position) > 0.5f)
{
is_append_position = true;
}
}
//
if (is_append_position)
{
if (this.position_num > 0)
{
Vector3 distance = position - this.positions[this.position_num - 1];
distance *= 0.5f / distance.magnitude;
position = this.positions[this.position_num - 1] + distance;
}
this.positions[this.position_num] = position;
this.position_num++;
// LineRender を作り直しておく.
this.GetComponent<LineRenderer>().SetVertexCount(this.position_num);
for (int i = 0; i < this.position_num; i++)
{
this.GetComponent<LineRenderer>().SetPosition(i, this.positions[i]);
}
}
}
break;
}
}
// 『create』ボタンを押したとき.
public void onCreateButtonPressed()
{
if (this.step == STEP.DRAWED)
{
this.next_step = STEP.CREATED;
}
}
// 『clear』ボタンを押したとき.
public void onRemoveButtonPressed()
{
if (this.step == STEP.DRAWED)
{
this.next_step = STEP.IDLE;
}
if (this.step == STEP.CREATED)
{
this.next_step = STEP.IDLE;
}
}
// 『push』ボタンを押したとき.
public void onPushButtonPressed()
{
push_domino.GetComponent<Rigidbody>().AddForce(push_domino.transform.forward, ForceMode.VelocityChange);
}
// マウスの位置を、3D空間のワールド座標に変換する.
//
// ・マウスカーソルとカメラの位置を通る直線
// ・ピースの中心を通る、水平な面
// ↑の二つが交わるところを求めます.
//
private Vector3 unproject_mouse_position()
{
Vector3 mouse_position = Input.mousePosition;
// ピースの中心を通る、水平(法線がY軸。XZ平面)な面.
Plane plane = new Plane(Vector3.up, new Vector3(0.0f, 0.0f, 0.0f));
// カメラ位置とマウスカーソルの位置を通る直線.
Ray ray = this.game_camera.GetComponent<Camera>().ScreenPointToRay(mouse_position);
// 上の二つが交わるところを求める.
float depth;
plane.Raycast(ray, out depth);
Vector3 world_position;
world_position = ray.origin + ray.direction * depth;
return (world_position);
}
}
|
9cdd27dac4d8f544ef7644f9e620b579507333bc
|
C#
|
xescrp/breinstormin
|
/breinstormin/breinstormin.tools/amazon/S3Engine.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Amazon.S3;
using Amazon;
using Amazon.S3.Model;
namespace breinstormin.tools.amazon
{
public class S3Engine
{
public static string BUCKET_NAME = System.Configuration.ConfigurationManager.AppSettings["S3Bucket"];
public static string S3_KEY = System.Configuration.ConfigurationManager.AppSettings["S3Key"];
public static AmazonS3 GetS3Client()
{
if (string.IsNullOrEmpty(BUCKET_NAME)) { BUCKET_NAME = "s3-bucket-name"; }
System.Collections.Specialized.NameValueCollection appConfig =
System.Configuration.ConfigurationManager.AppSettings;
AmazonS3 s3Client = AWSClientFactory.CreateAmazonS3Client(
appConfig["AWSAccessKey"],
appConfig["AWSSecretKey"]
);
return s3Client;
}
private static void CreateBucket(AmazonS3 client, string bucketname)
{
Console.Out.WriteLine("Checking S3 bucket with name " + bucketname);
ListBucketsResponse response = client.ListBuckets();
bool found = false;
foreach (S3Bucket bucket in response.Buckets)
{
if (bucket.BucketName == bucketname)
{
Console.Out.WriteLine(" Bucket found will not create it.");
found = true;
break;
}
}
if (found == false)
{
Console.Out.WriteLine(" Bucket not found will create it.");
client.PutBucket(new PutBucketRequest().WithBucketName(bucketname));
Console.Out.WriteLine("Created S3 bucket with name " + bucketname);
}
}
public static string CreateNewFile(AmazonS3 client, string filepath)
{
String S3_KEY = System.IO.Path.GetFileName(filepath);
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(S3_KEY);
request.WithFilePath(filepath);
//request.WithContentBody("This is body of S3 object.");
client.PutObject(request);
return S3_KEY;
}
public static string CreateNewFolder(AmazonS3 client, string foldername)
{
String S3_KEY = foldername;
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(S3_KEY);
request.WithContentBody("");
client.PutObject(request);
return S3_KEY;
}
public static string CreateNewFileInFolder(AmazonS3 client, string foldername, string filepath)
{
String S3_KEY = foldername + "/" + System.IO.Path.GetFileName(filepath);
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(S3_KEY);
request.WithFilePath(filepath);
//request.WithContentBody("This is body of S3 object.");
client.PutObject(request);
return S3_KEY;
}
public static string UploadFile(AmazonS3 client, string filepath)
{
//S3_KEY is name of file we want upload
S3_KEY = System.IO.Path.GetFileName(filepath);
PutObjectRequest request = new PutObjectRequest();
request.WithBucketName(BUCKET_NAME);
request.WithKey(S3_KEY);
//request.WithInputStream(MemoryStream);
request.WithFilePath(filepath);
client.PutObject(request);
return S3_KEY;
}
public static System.IO.MemoryStream GetFile(AmazonS3 s3Client, string filekey)
{
using (s3Client)
{
S3_KEY = filekey;
System.IO.MemoryStream file = new System.IO.MemoryStream();
try
{
GetObjectResponse r = s3Client.GetObject(new GetObjectRequest()
{
BucketName = BUCKET_NAME,
Key = S3_KEY
});
try
{
long transferred = 0L;
System.IO.BufferedStream stream2 = new System.IO.BufferedStream(r.ResponseStream);
byte[] buffer = new byte[0x2000];
int count = 0;
while ((count = stream2.Read(buffer, 0, buffer.Length)) > 0)
{
file.Write(buffer, 0, count);
}
}
finally
{
}
return file;
}
catch (AmazonS3Exception)
{
//Show exception
}
}
return null;
}
public static void DeleteFile(AmazonS3 Client, string filekey)
{
DeleteObjectRequest request = new DeleteObjectRequest()
{
BucketName = BUCKET_NAME,
Key = filekey
};
S3Response response = Client.DeleteObject(request);
}
public static void CopyFile(AmazonS3 s3Client, string sourcekey, string targetkey)
{
String destinationPath = targetkey;
CopyObjectRequest request = new CopyObjectRequest()
{
SourceBucket = BUCKET_NAME,
SourceKey = sourcekey,
DestinationBucket = BUCKET_NAME,
DestinationKey = targetkey
};
CopyObjectResponse response = s3Client.CopyObject(request);
}
public static void ShareFile(AmazonS3 s3Client, string filekey)
{
S3Response response1 = s3Client.SetACL(new SetACLRequest()
{
CannedACL = S3CannedACL.PublicRead,
BucketName = BUCKET_NAME,
Key = filekey
});
}
public static String MakeUrl(AmazonS3 s3Client, string filekey)
{
string preSignedURL = s3Client.GetPreSignedURL(new GetPreSignedUrlRequest()
{
BucketName = BUCKET_NAME,
Key = filekey,
Expires = System.DateTime.Now.AddYears(10)
});
return preSignedURL;
}
}
}
|
2c63ea57a1f2080f752f98f237096ab1037b8bb3
|
C#
|
nhuttrinh/446-Project2
|
/checkCreditNum.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
namespace Assignment3WF
{
public sealed class checkCreditNum : CodeActivity
{// Define an activity input argument of type string
public InArgument<string> CreditNumber { get; set; }
public OutArgument<Boolean> CreditResult { get; set; }
// If your activity returns a value, derive from CodeActivity<TResult>
// and return the value from the Execute method.
protected override void Execute(CodeActivityContext context)
{
// Obtain the runtime value of the CreditNumber input argument
string creditNum = context.GetValue(CreditNumber);
int sum = 0;//sum total
int[] arr = new int[16]; //initalize an array for digits
bool check = false;//used to separate between digits. In this case, using 'check' to take even digits if it is true.
for (int i = 0; i <= 15; i++)
{
arr[i] = Convert.ToInt32(creditNum.Substring(i, 1)); //Covert digits to integer type
}
for (int i = 15; i >= 0; i--)
{
if (check) //Start from the right side of card number, separate even and odd digits.
{
arr[i] = arr[i] * 2; // Double the digits
if (arr[i] > 9) //If the result is greater than 9
{
arr[i] = arr[i] - 9; //Then minus 9
}
}
sum = sum + arr[i]; //Adding digits to the sum
check = !check;//Switch the state of check
}
if (sum % 10 == 0)
{
context.SetValue(CreditResult, true);//return true if the sum is divisible by 10
}
else
{
context.SetValue(CreditResult, false);//return false if the sum is not divisible by 10
}
}
}
}
|
309e229770f8e82faa53b9ffa271a43d7217aa29
|
C#
|
QuintenVerheij/Omgevingswet
|
/AR/Assets/Scripts/Model/JSONModelUtility.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using Newtonsoft.Json;
using System;
[Serializable]
public class JSONModel {
[SerializeField] public int modelIndex;
[SerializeField] public Vector3 position;
[SerializeField] public Quaternion rotation;
[SerializeField] public Vector3 scale;
}
[Serializable]
public class JSONCombinedModel {
[SerializeField] public string name;
[SerializeField] public JSONModel[] models;
public JSONCombinedModel(CombinedModel combinedModel) {
Debug.Log($"[ExportCustomModel] combinedModel name: {combinedModel.transform.name}, child count: {combinedModel.transform.childCount}");
this.models = new JSONModel[combinedModel.modelIndices.Count];
if (combinedModel.modelIndices.Count != combinedModel.transform.childCount) {
Debug.LogError("Amount of modelIndices and children of combined model SHOULD BE EQUAL!");
}
name = combinedModel.name;
for (int i = 0; i < this.models.Length; i++) {
Transform child = combinedModel.transform.GetChild(i);
//Debug.Log($"[ExportCustomModel] {i}, child name: {child.name}");
this.models[i] = new JSONModel
{
modelIndex = combinedModel.modelIndices[i],
position = child.transform.localPosition,
rotation = child.transform.localRotation,
scale = child.transform.localScale
};
}
}
public static string ToJSON(JSONCombinedModel model) {
return JsonUtility.ToJson(model, true);
}
public static JSONCombinedModel FromJSON(string json) {
return JsonUtility.FromJson<JSONCombinedModel>(json);
}
}
public class JSONModelUtility : MonoBehaviour
{
public static bool CanCombineModels(Model[] models) {
bool containsCustomModel = false;
if (models.Length < 2) {
return false;
}
foreach (var model in models) {
if (model.IsCustomModel) {
containsCustomModel = true;
}
}
return !containsCustomModel;
}
public static string ExportCustomModel(string localPath, CombinedModel combinedModel) {
string path = Application.persistentDataPath + "/" + localPath + ".json";
JSONCombinedModel jsonModel = new JSONCombinedModel(combinedModel);
string json = JSONCombinedModel.ToJSON(jsonModel);
Debug.Log("JSON CONTENT:\n"+json);
Debug.Log("Exporting json file to '" + path + "'");
File.WriteAllText(path, json);
return path;
}
public static CombinedModel JSONModelToCombinedModel(JSONCombinedModel jsonCombinedModel, Transform parent, string name) {
Model[] modelPrefabs = LoadPrefabModels(jsonCombinedModel);
Model[] tempSceneModels = new Model[modelPrefabs.Length];
for (int i = 0; i < modelPrefabs.Length; i++) {
GameObject modelObject = Instantiate(modelPrefabs[i].gameObject, parent);
tempSceneModels[i] = modelObject.GetComponent<Model>();
tempSceneModels[i].transform.localPosition = jsonCombinedModel.models[i].position;
tempSceneModels[i].transform.localRotation = jsonCombinedModel.models[i].rotation;
tempSceneModels[i].transform.localScale = jsonCombinedModel.models[i].scale;
}
return CombineModels(tempSceneModels, parent, name);
}
public static CombinedModel ImportCustomModel(string localPath, Transform parent) {
string path = Application.persistentDataPath + "/" + localPath + ".json";
Debug.Log("Importing json file from '" + path + "'");
string json = File.ReadAllText(path);
JSONCombinedModel jsonCombinedModel = JSONCombinedModel.FromJSON(json);
return JSONModelToCombinedModel(jsonCombinedModel, parent, jsonCombinedModel.name);
}
private static Model[] LoadPrefabModels(Model[] sceneModels) {
Model[] models = new Model[sceneModels.Length];
for(int i = 0; i < sceneModels.Length; i++) {
int index = sceneModels[i].modelIndex;
models[i] = ObjectCreationHandler.Instance.models[index];
}
return models;
}
private static Model[] LoadPrefabModels(JSONCombinedModel combinedModel) {
Model[] models = new Model[combinedModel.models.Length];
for (int i = 0; i < combinedModel.models.Length; i++) {
int index = combinedModel.models[i].modelIndex;
models[i] = ObjectCreationHandler.Instance.models[index];
}
return models;
}
public static string[] GetListOfJSONFileNames() {
string path = Application.persistentDataPath + "/";
var info = new DirectoryInfo(path);
var fileInfo = info.GetFiles();
List<string> jsonFiles = new List<string>();
foreach (var file in fileInfo) {
if (file.Extension == ".json") {
string filename = file.Name.Replace(".json", "");
jsonFiles.Add(filename);
}
}
return jsonFiles.ToArray();
}
public static CombinedModel CombineModels(Model[] sceneModels, Transform parent, string modelName) {
GameObject combinedModelObject = new GameObject(modelName);
combinedModelObject.transform.localScale = parent.lossyScale;
combinedModelObject.transform.parent = parent;
Model[] prefabModels = LoadPrefabModels(sceneModels);
Model mainModel = prefabModels[0];
Model modelCopy = combinedModelObject.AddComponent<Model>();
mainModel.CopyTo(modelCopy);
CombinedModel combinedModel = combinedModelObject.AddComponent<CombinedModel>();
for (int i = 0; i < sceneModels.Length; i++) {
combinedModel.modelIndices.Add(prefabModels[i].modelIndex);
}
Vector3 positionSum = new Vector3();
for(int i = 0; i < sceneModels.Length; i++) {
positionSum += sceneModels[i].transform.position;
}
Vector3 averagePosition = new Vector3(positionSum.x / sceneModels.Length, positionSum.y / sceneModels.Length, positionSum.z / sceneModels.Length);
combinedModelObject.transform.position = averagePosition;
for (int i = 0; i < sceneModels.Length; i++) {
GameObject newModel = Instantiate(prefabModels[i].gameObject);
//newModel.transform.localPosition = combinedModelObject.transform.localPosition - sceneModels[i].transform.localPosition;
newModel.transform.position = sceneModels[i].transform.position;
newModel.transform.rotation = sceneModels[i].transform.rotation;
newModel.transform.localScale = sceneModels[i].transform.lossyScale;
newModel.transform.parent = combinedModelObject.transform;
DestroyImmediate(newModel.GetComponent<Model>());
CombinedModelPart part = newModel.AddComponent<CombinedModelPart>();
part.model = modelCopy;
}
for (int i = 0; i < sceneModels.Length; i++) {
Destroy(sceneModels[i].gameObject);
}
return combinedModel;
}
}
|
f8736d36933dee6ccf922c2c61a3cd653756c2a4
|
C#
|
andrew-moore-octo/CspUtils
|
/CspUtil.Tests/ParserFixture.cs
| 2.59375
| 3
|
using CspUtils;
using FluentAssertions;
using NUnit.Framework;
namespace CspUtil.Tests
{
public class Parse
{
[Test]
public void CanParseASimplePolicy()
{
var actual = Parser.Parse("script-src octopus.com");
var expected = new Csp(
new CspDirective("script-src", "octopus.com")
);
actual.Should().Be(expected);
}
[Test]
public void CanParseAComplexPolicy()
{
var actual = Parser.Parse("default-src 'self'; script-src 'self' octopus.com; connect-src octopus.com");
var expected = new Csp(
new CspDirective("default-src", "'self'"),
new CspDirective("script-src", "'self'", "octopus.com"),
new CspDirective("connect-src", "octopus.com")
);
actual.Should().Be(expected);
}
}
}
|
93b76d6c23287430939c20c623127bf0f0e51c7b
|
C#
|
BuzkoYaroslav/DecisionMakingMethods
|
/DecisionMakingMethods/DecisionMakingMethods/Methods/RandomizedMethod.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using NumericalAnalysisLibrary.MathStructures;
using NumericalAnalysisLibrary.Functions;
namespace DecisionMakingMethods.Methods
{
public abstract class RandomizedMethod : DecisionMakingMethod
{
protected abstract float WeightForPointUpper(PointF point);
protected abstract float WeightForPointDown(PointF point);
protected abstract MathFunction UpperOptimalLevelLine(double loss);
protected abstract MathFunction DownOptimalLevelLine(double loss);
protected virtual Tuple<double[], double, PointF> DetermineSolution(List<Tuple<int, PointF>> northwesternCorner, int solutionsCount)
{
var solution = new double[solutionsCount];
var upPart = northwesternCorner.Where(item => item.Item2.Y >= item.Item2.X).ToList();
var downPart = northwesternCorner.Where(item => item.Item2.Y < item.Item2.X).ToList();
var downWeight = downPart.Min(item => WeightForPointDown(item.Item2));
var downBest = downPart.Find(item => WeightForPointDown(item.Item2) == downWeight);
var upWeight = upPart.Min(item => WeightForPointUpper(item.Item2));
var upBest = upPart.Find(item => WeightForPointUpper(item.Item2) == upWeight);
var x = (downBest.Item2.Y - downBest.Item2.X) / (upBest.Item2.X - downBest.Item2.X + downBest.Item2.Y - upBest.Item2.Y);
var middleWeight = x * upBest.Item2.X + (1 - x) * downBest.Item2.X;
var middlePoint = new PointF(middleWeight, middleWeight);
if (middleWeight <= downWeight && middleWeight <= upWeight)
{
solution[upBest.Item1] = x;
solution[downBest.Item1] = 1 - x;
return new Tuple<double[], double, PointF>(solution, middleWeight, middlePoint);
}
else if (downWeight <= middleWeight && downWeight <= upWeight)
{
solution[downBest.Item1] = 1;
return new Tuple<double[], double, PointF>(solution, downWeight, downBest.Item2);
}
else
{
solution[upBest.Item1] = 1;
return new Tuple<double[], double, PointF>(solution, upWeight, upBest.Item2);
}
}
public override object Solve(Matrix qMatrix)
{
if (qMatrix.ColumnsCount != 2)
{
throw new ArgumentException("Matrix columns count must be equal to 2!", "qMatrix");
}
var anchorMatrix = AnchorMatrix(qMatrix);
var points = GetPoints(anchorMatrix);
var convexHull = ConvexHull(points);
var northwesternPart = GetNorthWesternPart(convexHull);
var solution = DetermineSolution(northwesternPart, qMatrix.RowsCount);
return new Tuple<double[], double, PointF, Matrix, PointF[], Tuple<int, PointF>[], Tuple<int, PointF>[], Tuple<MathFunction, MathFunction>>(
solution.Item1,
solution.Item2,
solution.Item3,
anchorMatrix,
points.Select(item => item.Item2).ToArray(),
convexHull.ToArray(),
northwesternPart.ToArray(),
new Tuple<MathFunction, MathFunction>(UpperOptimalLevelLine(solution.Item2), DownOptimalLevelLine(solution.Item2)));
}
protected virtual Matrix AnchorMatrix(Matrix qMatrix)
{
return GetLossesMatrix(qMatrix);
}
protected List<Tuple<int, PointF>> GetPoints(Matrix matrix)
{
var points = new List<Tuple<int, PointF>>();
for (int i = 0; i < matrix.RowsCount; i++)
{
points.Add(new Tuple<int, PointF>(i, new PointF((float)matrix[i, 0], (float)matrix[i, 1])));
}
return points;
}
protected List<Tuple<int, PointF>> ConvexHull(List<Tuple<int, PointF>> points)
{
if (points.Count < 3)
{
return points;
}
List<Tuple<int, PointF>> hull = new List<Tuple<int, PointF>>();
// get leftmost point
var minX = points.Min(item => item.Item2.X);
Tuple<int, PointF> vPointOnHull = points.Where(item => item.Item2.X == minX).First();
Tuple<int, PointF> vEndpoint;
do
{
hull.Add(vPointOnHull);
vEndpoint = points[0];
for (int i = 1; i < points.Count; i++)
{
if ((vPointOnHull.Item2 == vEndpoint.Item2)
|| (Orientation(vPointOnHull.Item2, vEndpoint.Item2, points[i].Item2) == -1))
{
vEndpoint = points[i];
}
}
vPointOnHull = vEndpoint;
}
while (vEndpoint != hull[0]);
return hull;
}
private int Orientation(PointF p1, PointF p2, PointF p)
{
// Determinant
float Orin = (p2.X - p1.X) * (p.Y - p1.Y) - (p.X - p1.X) * (p2.Y - p1.Y);
if (Orin > 0)
return -1; // (* Orientation is to the left-hand side *)
if (Orin < 0)
return 1; // (* Orientation is to the right-hand side *)
return 0; // (* Orientation is neutral aka collinear *)
}
protected List<Tuple<int, PointF>> GetNorthWesternPart(List<Tuple<int, PointF>> points)
{
var minY = points.Min(point => point.Item2.Y);
var minX = points.Min(point => point.Item2.X);
var pointX = points.Find(point => point.Item2.X == minX);
var pointY = points.Find(point => point.Item2.Y == minY);
var northwestern = points.Where(point => (point.Item2.X >= pointX.Item2.X && point.Item2.X <= pointY.Item2.X) &&
(point.Item2.Y >= pointY.Item2.Y && point.Item2.Y <= pointX.Item2.Y))
.ToList();
var origin = new PointF(0, 0);
northwestern.Sort((p1, p2) => Orientation(p1.Item2, p2.Item2, origin));
return northwestern;
}
}
}
|
163be80f1dea8ce940c2bb61abb1052cab1466c3
|
C#
|
viraco4a/SoftUni
|
/CSharpFundamentals/CSharpOOPbasics/InterfacesAndAbstractionEx/Ferrari/StartUp.cs
| 2.5625
| 3
|
using System;
namespace Ferrari
{
public class StartUp
{
static void Main(string[] args)
{
string driver = Console.ReadLine();
ICar ferrary = new Ferrari(driver);
Console.WriteLine(ferrary);
}
}
}
|
6022ca5b19aa2619136f90b69202d5d044459381
|
C#
|
agentsquash/AS_Prog
|
/AS_Prog/ASCII_Designer.cs
| 3.421875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AS_Prog
{
class ASCII_Designer
{
public static void Run()
{
var dict = new Dictionary<int, string[]>
{
{97, new string[]{ "+", " ", " ", " ", " ", " ", " ", " ", " ", " " }},
{98, new string[]{ "+", "+", " ", " ", " ", " ", " ", " ", " ", " " }},
{99, new string[]{ "+", "+", "-", " ", " ", " ", " ", " ", " ", " " }},
{100, new string[]{ "+", "+", "-", "-", " ", " ", " ", " ", " ", " " }},
{101, new string[]{ "+", "+", "-", "-", "*", " ", " ", " ", " ", " " }},
{102, new string[]{ "+", "+", "-", "-", "*", "*", " ", " ", " ", " " }},
{103, new string[]{ "+", "+", "-", "-", "*", "*", "*", " ", " ", " " }},
{104, new string[]{ "+", "+", "-", "-", "*", "*", "*", ".", " ", " " }},
{105, new string[]{ "+", "+", "-", "-", "*", "*", "*", ".", ".", " " }},
{106, new string[]{ "+", "+", "-", "-", "*", "*", "*", ".", ".", "." }} };
string[] lines = new string[10];
int shift = 0;
Console.Write("Enter your design: ");
char[] input = Console.ReadLine().ToCharArray();
for (int n = 0; n < input.Length; n++)
{
int value = Convert.ToInt32(input[n]); // ASCII values
if (value > 47 && value < 59) // If ASCII == digit
{
shift = (value - 48); // Converts ASCII value to shift digit.
}
else if (value > 96 && value < 107) // If lower case letter.
{
for (int i = 0; i < shift; i++)
{
lines[i] += " ";
}
for (int i = 0; i+shift < lines.Length; i++) // Prints up to line shift.
{
lines[i+shift] += dict[value][i];
}
shift = 0;
}
else // ASCII value is invalid.
Console.WriteLine("Invalid input");
}
for (int i = 9; i > 0; i--)
{
Console.WriteLine(lines[i]);
}
}
}
}
|
b08f5e890e7062483a41c4c4b8184696d624852d
|
C#
|
HCMUSAssignmentWarehouse/spamming-pool
|
/C#/Console/TestConstructor/TestConstructor/Child.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestConstructor
{
class Child : Base
{
public Child() : base(1)
{
Console.WriteLine("Child constructor called");
}
public Child(int i) : base(i)
{
Console.WriteLine("Child i constructor called");
}
public void Foo()
{
//base.Foo();
Console.WriteLine("Foo");
}
}
}
|
a72db1aee4767295fb701e5250f430782fc0f7bf
|
C#
|
Gabrity/ObjectOrientedDesignPatterns
|
/Behavioral/TemplateMethod/CarManufactureTemplate.cs
| 3.046875
| 3
|
using System;
namespace TemplateMethod
{
public abstract class CarManufactureTemplate
{
public void ManufactureCar()
{
GenerateChassis();
ApplyPaint();
InstallDriveTrain();
InstallInterior();
InstallExtras();
}
protected abstract void GenerateChassis();
protected abstract void ApplyPaint();
protected abstract void InstallDriveTrain();
protected abstract void InstallInterior();
protected virtual void InstallExtras()
{
Console.WriteLine("No extras by default");
}
}
}
|
6fa1719f003f828f59aa1cfdec19d8de1517ad3f
|
C#
|
henriq20/tic-tac-toe
|
/src/TicTacToe.Demo.ConsoleApp/TicTacToeGame.cs
| 3.140625
| 3
|
using System;
using TicTacToe.Core;
using TicTacToe.Core.Players;
namespace TicTacToe.Demo.ConsoleApp
{
public class TicTacToeGame
{
public IPlayer Player { get; set; }
public IPlayer Opponent { get; set; }
private BoardDisplayer boardDisplayer;
public void ShowTurn(IPlayer currentPlayer)
{
Output.Write("Turn: ");
PrintMark(currentPlayer.Mark);
Output.WriteLine();
}
public void ShowWinner(TicTacToeMatchResult? matchResult)
{
switch (matchResult)
{
case TicTacToeMatchResult.Tie:
Output.WriteLine("The game ended in a TIE, nobody won.");
break;
case TicTacToeMatchResult.CrossWin:
PrintMark(MarkType.Cross);
Output.WriteLine(" won!");
break;
case TicTacToeMatchResult.CircleWin:
PrintMark(MarkType.Circle);
Output.WriteLine(" won!");
break;
default:
break;
}
}
public void ShowOptions()
{
Output.WriteLine("Options:\n");
Output.Write("1", ConsoleColor.Yellow);
Output.WriteLine(" - Play against a computer");
Output.Write("2", ConsoleColor.Yellow);
Output.WriteLine(" - Play against a friend");
Output.Write("3", ConsoleColor.Yellow);
Output.WriteLine(" - Exit");
}
public void ShowDifficultyLevels()
{
Output.WriteLine("Difficulty levels:\n");
Output.Write("1", ConsoleColor.Yellow);
Output.WriteLine(" - Easy");
Output.Write("2", ConsoleColor.Yellow);
Output.WriteLine(" - Medium");
Output.Write("3", ConsoleColor.Yellow);
Output.WriteLine(" - Impossible");
}
public void ShowScore()
{
PrintMark(MarkType.Cross);
Output.Write(" => ");
Output.WriteLine(Player.Score.Wins, ConsoleColor.Blue);
PrintMark(MarkType.Circle);
Output.Write(" => ");
Output.WriteLine(Opponent.Score.Wins, ConsoleColor.Red);
Output.WriteLine();
}
public void PrintMark(MarkType mark)
{
if (mark == MarkType.Cross)
{
Output.Write("X", ConsoleColor.Blue);
return;
}
Output.Write("O", ConsoleColor.Red);
}
}
}
|
ab6f48f92be5306b002c04f854cd766d87e6a63f
|
C#
|
264dormitory/dotnet
|
/planeTicketBooking/planeTicketBooking/Controllers/AirportAdminController.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using planeTicketBooking.Models;
using System.Data;
using MySql.Data.MySqlClient; //导入连接使用MySQL数据库所必须的命名空间
/// <summary>
/// 李世杰创建
///
/// 用于:
/// 1、机场信息管理页面
/// 1.1、机场名称设置
/// </summary>
/// <warning>
/// 为了辨别方便,创建的控制器的名称应该和页面的一致
/// </warning>
namespace planeTicketBooking.Controllers
{
public class AirportAdminController : Controller
{
// GET: 绑定机场名称设置页面的视图
public ActionResult airportname_set()
{
CityListModels cityList = new CityListModels();
//建立City Model列表
List<City> cityArray = new List<City>();
//连接数据库
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost;Database=ticket;User ID=admin;Password=admin;port=3306;CharSet=utf8;pooling=true;SslMode=None;";
//获取City数据表中的所有数据
string cityMsg = String.Format("select * from city");
MySqlCommand comm = new MySqlCommand(cityMsg, conn);
//创建和初始化数据适配器DataAdapter
MySqlDataAdapter cityAdapter = new MySqlDataAdapter(cityMsg, conn);
//创建DataSet对象
DataSet cityDataSet = new DataSet();
try
{
conn.Open();
cityAdapter.Fill(cityDataSet, "city"); //将DataSet起名为city
//使用DataTable来提取DataSet表中的数据
DataTable cityDataTable = cityDataSet.Tables["city"];
//将DataTable中的数据赋值到List之中
for (int row = 0; row < cityDataTable.Rows.Count; row++)
{
City city = new City();
city.CityId = Convert.ToInt16(cityDataTable.Rows[row]["id"]);
city.CityName = cityDataTable.Rows[row]["city_name"].ToString();
city.AirportName = cityDataTable.Rows[row]["airport_name"].ToString();
cityArray.Add(city);
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cityList.CityArray = cityArray;
conn.Close();
}
return View(cityList);
}
/// <summary>
/// 用于添加城市信息数据
/// </summary>
[HttpPost]
public string AddCityMsg(string airportname, string cityname)
{
CityListModels cityList = new CityListModels();
//建立City Model列表
List<City> cityArray = new List<City>();
//连接数据库
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost;Database=ticket;User ID=admin;Password=admin;port=3306;CharSet=utf8;pooling=true;SslMode=None;";
//获取City数据表中的所有数据
string add = String.Format("insert into city (airport_name, city_name) values (\'{0}\', \'{1}\')", airportname, cityname);
MySqlCommand comm = new MySqlCommand(add, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
return "数据新增成功";
}
/// <summary>
/// 用于修改城市信息数据
/// </summary>
[HttpPost]
public string ChangeCityMsg(string airportID, string airportName)
{
CityListModels cityList = new CityListModels();
//建立City Model列表
List<City> cityArray = new List<City>();
//连接数据库
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost;Database=ticket;User ID=admin;Password=admin;port=3306;CharSet=utf8;pooling=true;SslMode=None;";
//获取City数据表中的所有数据
string change = String.Format("update city set airport_name = \'{1}\' where id = \'{0}\'", airportID, airportName);
MySqlCommand comm = new MySqlCommand(change, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
return "数据修改成功";
}
/// <summary>
/// 用于删除城市信息数据
/// </summary>
[HttpPost]
public string DeleteCityMsg(string airportID)
{
CityListModels cityList = new CityListModels();
//建立City Model列表
List<City> cityArray = new List<City>();
//连接数据库
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost;Database=ticket;User ID=admin;Password=admin;port=3306;CharSet=utf8;pooling=true;SslMode=None;";
//获取City数据表中的所有数据
string delete = String.Format("delete from city where id = \'{0}\'", airportID);
MySqlCommand comm = new MySqlCommand(delete, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
return "数据删除成功";
}
}
}
|
c93349ec6de2fb9817e13a7bb135f976e3a2362f
|
C#
|
Phanith15/GitHubLocRep
|
/C#HotelReservation/FrmInvoice.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI2
{
public partial class FrmInvoice : Form
{
AllPayments myPayment = new AllPayments();
double balance;
double taxamount;
public FrmInvoice()
{
InitializeComponent();
}
private void labelX3_Click(object sender, EventArgs e)
{
}
private void FrmInvoice_Load(object sender, EventArgs e)
{
// Disable Print button
btnXPrintReceipt.Enabled = false;
// Setting Payment types
cmdPaymentTypes.Items.Add("Cash");
cmdPaymentTypes.Items.Add("Eftpos");
cmdPaymentTypes.Items.Add("Credit");
cmdPaymentTypes.Items.Add("VISA");
cmdPaymentTypes.Items.Add("Cheque");
//Display all info
lblCustomerID.Text = Invoices.custIDFK;
lblBookedName.Text = Invoices.name;
lblPaymentDate.Text = Convert.ToString( DateTime.Today.ToShortDateString());
lblBookedID.Text = Invoices.bookingReference;
lblRoomID.Text = Invoices.roomBooked_ID;
lblRoomType.Text = Invoices.roomBooked_Type;
lblCheckInDate.Text = Convert.ToString( Invoices.firstDateOccupied.ToShortDateString());
lblCheckOutDate.Text = Convert.ToString( Invoices.lastDateOccupied.ToShortDateString());
lblBalance.Text ="$ "+ Convert.ToString(Invoices.balance_beforeTax) ;
}
private void btnXPrint_Click(object sender, EventArgs e)
{
PrintReceipt();
}
private void txtTaxRate_TextChanged(object sender, EventArgs e)
{
double taxrate;
try
{
taxrate = Convert.ToDouble(txtTaxRate.Text);
balance = Invoices.balance_beforeTax;
taxamount = taxrate * balance;
lblTaxAmount.Text = "$ " + Convert.ToString(taxamount);
}
catch (Exception)
{
MessageBox.Show("Invalid input type !");
}
}
private void btnXPay_Click(object sender, EventArgs e)
{
try
{
double totalpayment;
totalpayment = balance + taxamount;
Invoices.paymentType = cmdPaymentTypes.SelectedItem.ToString();
Invoices.taxRate = Convert.ToDouble(txtTaxRate.Text);
Invoices.taxAmount = taxamount;
Invoices.paymentTotal = totalpayment;
Invoices.InsertPayment();
// Enable Print button
btnXPrintReceipt.Enabled = true;
btnXPay.Enabled = false;
MessageBox.Show("Payment has been saved !");
}
catch (Exception)
{
MessageBox.Show("Missing data !");
}
}
private void PrintReceipt()
{
PrintDialog printDialog = new PrintDialog();
PrintDocument printDocument = new PrintDocument();
printDialog.Document = printDocument;
printDocument.PrintPage += new PrintPageEventHandler (printDocument_PrintPage);
DialogResult result = printDialog.ShowDialog();
if (result == DialogResult.OK)
{
printDocument.Print();
}
}
void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics graphic = e.Graphics;
Font font = new Font("Courier New", 12);
Font font2 = new Font("Courier New", 14);
float fontHeight = font.GetHeight();
int startX = 10;
int startY = 10;
int offset = 40;
graphic.DrawString("Wifi-Hotel New Zealand".PadRight(30), new Font("Courier New", 20), new SolidBrush(Color.Black), startX, startY);
// Call which payment based on given customer ID
myPayment.GetPaymentDetail(lblCustomerID.Text);
// Pass all properties from Payments class to strings
string strCustomerIDFK = myPayment.custIDFK;
string strPaymentDate = myPayment.paymentDate.ToShortDateString();
string strFirstDateOccupied = myPayment.firstdateOccupied.ToShortDateString();
string strLastDateOccupied = myPayment.lastdateOccupied.ToShortDateString();
string strPaymentType = myPayment.paymentType;
string strTotalDay = myPayment.totalDay.ToString();
string strTaxRate = myPayment.taxRate.ToString();
string strTaxAmount = string.Format ("{0:c}", myPayment.taxAmount);
string strPaymentTotal = string.Format("{0:c}", myPayment.paymentTotal);
List<string> listpayments = new List<string>();
listpayments.Add(" ");
listpayments.Add(" ");
listpayments.Add("CustomerID : " + strCustomerIDFK);
listpayments.Add("Payment Date : " + strPaymentDate);
listpayments.Add("First date occupied : " + strFirstDateOccupied );
listpayments.Add("Last date occupied : " + strLastDateOccupied);
listpayments.Add("Total day : " + strTotalDay);
listpayments.Add("--------------------------------------------");
listpayments.Add("Payment type : " + strPaymentType);
listpayments.Add("Tax rate : " + strTaxRate);
listpayments.Add("Tax amount : " + strTaxAmount);
listpayments.Add("Total payment : " + strPaymentTotal);
listpayments.Add("--------------------------------------------");
listpayments.Add(" ");
//Iterate through the list and print out
foreach (var item in listpayments)
{
graphic.DrawString(item.PadRight(30), font, new SolidBrush(Color.Black), startX, startY + offset);
offset = offset + (int)fontHeight + 5;
}
offset = offset + 20;
graphic.DrawString("Total to pay : ".PadRight(30) + string.Format("{0:c}",strPaymentTotal),font2 ,new SolidBrush (Color.Black ),startX ,startY+offset);
}
}
}
|
1f8fbde09375ecb12b0b3de2ba818ffa1ba1318b
|
C#
|
thenitro/elements-of-programming-interviews
|
/ElementsOfProgrammingInterviews/ElementsOfProgrammingInterviews/StacksAndQueues/Problem_9_6.cs
| 3.1875
| 3
|
using System.Collections.Generic;
namespace ElementsOfProgrammingInterviews.StacksAndQueues
{
public class Problem_9_6
{
public int[] Solution(int[] buildings)
{
var stack = new Stack<int>();
foreach (var building in buildings)
{
while (stack.Count > 0 && building >= stack.Peek())
{
stack.Pop();
}
stack.Push(building);
}
return stack.ToArray();
}
}
}
|
d2259eb715b309bb394bd1d261a61c3f2b389d49
|
C#
|
quangvy/EPrescription
|
/BKUGen/ePrescription.Settings/Settings/CustomXmlSerializable.cs
| 2.71875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Globalization;
namespace ePrescription.Settings.Settings
{
public class CustomXmlSerializable : CustomSerializable, ICustomXmlSerializable
{
#region ICustomXmlSerializable Members
public void Deserialize(string str)
{
using (TextReader textReader = new StringReader(str))
using (XmlReader xmlReader = new XmlTextReader(textReader))
{
xmlReader.ReadStartElement();
xmlReader.ReadStartElement();
this.Id = new Guid(xmlReader.ReadContentAsString());
xmlReader.ReadEndElement();
xmlReader.ReadStartElement();
this.Value1 = xmlReader.ReadContentAsInt();
xmlReader.ReadEndElement();
xmlReader.ReadStartElement();
this.Value2 = xmlReader.ReadContentAsDateTime();
xmlReader.ReadEndElement();
xmlReader.ReadStartElement();
this.Value3 = xmlReader.ReadContentAsString();
xmlReader.ReadEndElement();
xmlReader.ReadStartElement();
this.Value4 = xmlReader.ReadContentAsDecimal();
xmlReader.ReadEndElement();
xmlReader.ReadEndElement();
}
}
public string Serialize()
{
StringBuilder result = new StringBuilder(100);
using (TextWriter textWriter = new StringWriter(result, CultureInfo.InvariantCulture))
using (XmlWriter xmlWriter = new XmlTextWriter(textWriter))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("CustomXmlSerializable");
xmlWriter.WriteStartElement("Id");
xmlWriter.WriteValue(this.Id.ToString());
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Value1");
xmlWriter.WriteValue(this.Value1);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Value2");
xmlWriter.WriteValue(this.Value2);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Value3");
xmlWriter.WriteValue(this.Value3);
xmlWriter.WriteEndElement();
xmlWriter.WriteStartElement("Value4");
xmlWriter.WriteValue(this.Value4);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
}
return result.ToString();
}
#endregion
}
}
|
69037af78e48c28b0566b8bb17379ff119ffbd0d
|
C#
|
KeSaga/01_GitHubWorkSpace
|
/Lyf.DrawingLibrary/Lyf.DrawingLibrary/2D/Chart.cs
| 2.96875
| 3
|
using Lyf.DrawingLibrary.Common;
using System;
using System.Drawing;
using System.Runtime.Serialization;
using System.Security.Permissions;
namespace Lyf.DrawingLibrary._2D
{
[Serializable]
public class Chart : ICloneable, ISerializable
{
#region 常量
/// <summary>
/// 当前的 schema 值用于定义序列化文件的版本号
/// </summary>
public const int SCHEMA = 10;
#endregion
#region 变量
/// <summary>
/// 通过坐标轴限定图形区域的矩形
/// </summary>
internal RectangleF _rect;
/// <summary>
/// 用于存储图形区域的 Border 的数值,通过属性 <see cref="Border"/> 访问
/// </summary>
internal Border _border;
/// <summary>
/// 用于定义 <see cref="Rect"/> 是否自动调整大小,通过属性 <see cref="IsRectAuto"/> 访问
/// </summary>
internal bool _isRectAuto;
#endregion
#region 属性
/// <summary>
/// 获取或设置由坐标轴(<see cref="XAxis"/>、<see cref="YAxis"/>、<see cref="Y2Axis"/>)限定的包含图
/// 形区域边界的长方形区域。如果将该值设置为手工方式获取,则 <see cref="IsRectAuto"/> 将被自动设置为 false
/// </summary>
public RectangleF Rect
{
get { return _rect; }
set
{
_rect = value;
_isRectAuto = false;
}
}
/// <summary>
/// 获取或设置图形区域的边框值
/// </summary>
public Border Border
{
get { return _border; }
set { _border = value; }
}
/// <summary>
/// 获取或设置一个布尔值,该值用于定义是否自动计算 Rect (绝大多数情况都是 true)
/// </summary>
public bool IsRectAuto
{
get { return _isRectAuto; }
set { _isRectAuto = value; }
}
#endregion
#region 构造函数
/// <summary>
/// 构造函数
/// </summary>
public Chart()
{
this._isRectAuto = true;
this._border = new Border(Default.IsBorderVisible, Default.BorderColor, Default.BorderPenWidth);
}
/// <summary>
/// 克隆一个当前实例的一个副本(深度克隆)
/// </summary>
/// <param name="chart"></param>
public Chart(Chart chart)
{
_border = chart._border.Clone();
_rect = chart._rect;
_isRectAuto = chart._isRectAuto;
}
/// <summary>
/// 实现反序列化的构造函数
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public Chart(SerializationInfo info, StreamingContext context)
{
int sch = info.GetInt32(CommonConsts.SCHEMASTRING);
_rect = (RectangleF)info.GetValue("rect", typeof(RectangleF));
_border = (Border)info.GetValue("border", typeof(Border));
_isRectAuto = info.GetBoolean("isRectAuto");
}
#endregion
#region ICloneable 接口实现
object ICloneable.Clone()
{
return this.Clone();
}
#endregion
#region ISerializable 接口实现
/// <summary>
/// 实现反序列化
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(CommonConsts.SCHEMASTRING, SCHEMA);
info.AddValue("rect", _rect);
info.AddValue("border", _border);
info.AddValue("isRectAuto", _isRectAuto);
}
#endregion
#region 函数
/// <summary>
/// 实现深度克隆
/// </summary>
/// <returns></returns>
public Chart Clone()
{
return new Chart(this);
}
#endregion
#region Defaults Struct
/// <summary>
/// 用于定义 Chart 的默认值的结构
/// </summary>
public struct Default
{
/// <summary>
/// <see cref="Chart"/> 边框的默认颜色
/// (<see cref="Chart.Border"/> 属性).
/// </summary>
public static Color BorderColor = Color.Black;
/// <summary>
/// 绘制 <see cref="GraphPane.Chart"/> 边框的默认笔宽
/// (<see cref="Chart.Border"/> 属性).
/// 单位:点 (1/72 英寸).
/// </summary>
public static float BorderPenWidth = 1F;
/// <summary>
/// 定义默认显示 <see cref="Chart"/> 边框
/// (<see cref="Chart.Border"/> 属性).
/// </summary>
public static bool IsBorderVisible = true;
}
#endregion
}
}
|
b84caa26d0b515f29c7b0f2743b04adef51ffebd
|
C#
|
ERNICommunity/ActivityContext.NET
|
/src/ActivityContext.Integration.NLog/ActivitiesLayoutRenderer.cs
| 2.8125
| 3
|
using System.IO;
using System.Text;
using ActivityContext.Data;
using NLog;
using NLog.LayoutRenderers;
namespace ActivityContext.Integration.NLog
{
/// <summary>
/// A Layout renderer that outputs JSON serialized list of current activities.
/// <seealso href="https://github.com/nlog/nlog/wiki/Layout-Renderers"/>
/// <seealso cref="Activity.GetCurrentActivities"/>
/// </summary>
[LayoutRenderer("activities")]
public class ActivitiesLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Renders the current activities and appends it to the specified <paramref name="builder"/>.
/// </summary>
/// <param name="builder"><see cref="StringBuilder"/> to append the rendered data to</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
var activities = Activity.GetCurrentActivities();
var serializer = ActivityInfoList.DefaultJsonSerializer;
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, activities);
var json = Encoding.UTF8.GetString(ms.ToArray());
builder.Append(json);
}
}
}
}
|
7d3dffa0a457e3a26400098837981eae6858a888
|
C#
|
rvramesh/CallHirearchyWalker.API
|
/MethodDetailBuilder.cs
| 2.84375
| 3
|
/************************************************************************************************
* DICLAIMER : The below code is hacked over a weekend. This is not of a production quality
* and it is proved to be right and not wrong. Please use this code AS/IS and I am not
* responsible for damages caused. Software distributed under the License is distributed
* on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
*
* Written by Ramesh Vijayaraghavan, <contact@rvramesh.com>
*
*
* You are free to use this in any way you want, in case you find this useful or working for you.
* ***********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Collections.Generic;
namespace CallHirearchyWalker.API
{
static class MethodDetailBuilder
{
public static MethodDetail Create(MethodReference reference)
{
return Create(reference, null);
}
public static MethodDetail Create(MethodReference reference, List<MethodDetail> usedMethods)
{
StringBuilder builder = new StringBuilder();
builder.Append(reference.DeclaringType.FullName);
builder.Append("::");
builder.Append(reference.Name);
if (reference.HasGenericParameters)
{
GetGenericMethodInstanceFullName(reference.GenericParameters, builder);
}
GetParameters(reference, builder);
string fullName = reference.FullName;
return new MethodDetail(fullName, builder.ToString(), usedMethods,MethodDetailBuilder.Create(reference.DeclaringType));
}
private static DeclaringTypeDetail Create(TypeReference reference)
{
return new DeclaringTypeDetail(reference.FullName, reference.Name);
}
private static void GetParameters(MethodReference reference, StringBuilder builder)
{
builder.Append("(");
if (reference.HasParameters)
{
Collection<ParameterDefinition> parameters = reference.Parameters;
for (int i = 0; i < parameters.Count; i++)
{
ParameterDefinition definition = parameters[i];
if (i > 0)
{
builder.Append(",");
}
if (definition.ParameterType.IsSentinel)
{
builder.Append("...,");
}
TypeReference parameterType = definition.ParameterType;
if (parameterType is ByReferenceType)
{
parameterType = (parameterType as ByReferenceType).ElementType;
if (definition.IsOut)
{
builder.Append("out ");
}
else
{
builder.Append("ref ");
}
}
if ((parameterType.IsGenericInstance && (parameterType as GenericInstanceType).HasGenericArguments))
{
builder.Append(parameterType.Name.Substring(0, parameterType.Name.IndexOf("`")));
var paramType = parameterType as GenericInstanceType;
builder.Append("<");
for (int j = 0; j < paramType.GenericArguments.Count; j++)
{
if (j > 0)
{
builder.Append(",");
}
builder.Append(paramType.GenericArguments[j].Name);
}
builder.Append(">");
}
else
{
builder.Append(definition.ParameterType.Name.Replace("&",string.Empty));
}
}
}
builder.Append(")");
}
private static void GetGenericMethodInstanceFullName(Collection<GenericParameter> genericParams, StringBuilder builder)
{
builder.Append("<");
for (int i = 0; i < genericParams.Count; i++)
{
if (i > 0)
{
builder.Append(",");
}
builder.Append(genericParams[i].FullName);
}
builder.Append(">");
}
}
}
|
9db702eab4fe21cd469b9355b60bbb2ac44767bc
|
C#
|
cambell-prince/FieldWorks
|
/Src/Utilities/BasicUtils/BasicUtilsTests/ImagePictureTest.cs
| 2.625
| 3
|
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2009, SIL International. All Rights Reserved.
// <copyright from='2009' to='2009' company='SIL International'>
// Copyright (c) 2009, SIL International. All Rights Reserved.
//
// Distributable under the terms of either the Common Public License or the
// GNU Lesser General Public License, as specified in the LICENSING.txt file.
// </copyright>
#endregion
//
// File: IPicture.cs
// Responsibility: FW Team
// ---------------------------------------------------------------------------------------------
using System.Drawing;
using NUnit.Framework;
namespace SIL.Utils
{
/// ----------------------------------------------------------------------------------------
/// <summary>
/// Tests for ImagePicture class
/// </summary>
/// ----------------------------------------------------------------------------------------
[TestFixture]
public class ImagePictureTests // can't derive from BaseTest because of dependencies
{
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests the ImagePicture class
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void ImagePictureClass()
{
const int width = 100;
const int height = 200;
using (Image testImage = new Bitmap(width, height))
{
using (ImagePicture i = ImagePicture.FromImage(testImage))
{
Assert.AreEqual(new HiMetric(width, i.DpiX).Value, i.Width, "A1");
Assert.AreEqual(new HiMetric(height, i.DpiY).Value, i.Height, "A2");
}
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests HiMetric with 96 dpi
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void HimetricDpi96()
{
const int dpi = 96;
const int pixels = 100;
HiMetric h1 = new HiMetric(pixels, dpi);
HiMetric h2 = new HiMetric(h1.Value);
Assert.IsTrue(h2.Value == h1.Value, "A1");
Assert.IsTrue(h2.GetPixels(dpi) == h1.GetPixels(dpi), "A2");
Assert.IsTrue(h2.GetPixels(dpi) == pixels, "A3");
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Tests HiMetric with 200 dpi
/// </summary>
/// ------------------------------------------------------------------------------------
[Test]
public void HimetricDpi200()
{
const int dpi = 200;
const int pixels = 100;
HiMetric h1 = new HiMetric(pixels, dpi);
HiMetric h2 = new HiMetric(h1.Value);
Assert.IsTrue(h2.Value == h1.Value, "A1");
Assert.IsTrue(h2.GetPixels(dpi) == h1.GetPixels(dpi), "A2");
Assert.IsTrue(h2.GetPixels(dpi) == pixels, "A3");
}
}
}
|
b30eacf0be78ef9a624d49b6a81db7e83c517b4d
|
C#
|
LByrgeCP/CyberPatriot-Scoring-Report
|
/Configuration Tool/Configuration/Sections/ConfigUsers.cs
| 2.75
| 3
|
using Configuration_Tool.Configuration.Users;
using Configuration_Tool.Controls;
using Configuration_Tool.Controls.Users;
using System.IO;
namespace Configuration_Tool.Configuration.Sections
{
public class ConfigUsers : IConfig
{
public EConfigType Type => EConfigType.Users;
public MainWindow MainWindow { get; set; }
public void Load(BinaryReader reader)
{
// Clear current list of user settings
MainWindow.itemsUserConfig.Items.Clear();
// Number of user settings instances
int count = reader.ReadInt32();
// For each user settings instance
for (int i = 0; i < count; i++)
{
// Parse user settings instance from binary reader
UserSettings settings = UserSettings.Parse(reader);
// Create control from settings
ControlUserSettings control = new ControlUserSettings(settings);
// Add user settings to user settings items control
MainWindow.itemsUserConfig.Items.Add(control);
}
}
public void Save(BinaryWriter writer)
{
// Get number of user settings instances and write
int count = MainWindow.itemsUserConfig.Items.Count;
writer.Write(count);
// For each user settings control
foreach (ControlUserSettings control in MainWindow.itemsUserConfig.Items)
{
// Get user settings instance
UserSettings settings = control.Settings;
// Write user settings to stream
settings.Write(writer);
}
}
}
}
|
b06ec64aeb443aadda4ddd9127fffabc5fc24e47
|
C#
|
lukiffer/SpadesBot
|
/SpadesBot/Helpers/DeckFactory.cs
| 3.078125
| 3
|
using System.Collections.Generic;
using System.Linq;
using SpadesBot.Models;
namespace SpadesBot.Helpers
{
public static class DeckFactory
{
public static List<string> CreateStringDeck()
{
return new List<string> {
"As", "Ks", "Qs", "Js", "10s", "9s", "8s", "7s", "6s", "5s", "4s", "3s", "2s",
"Ah", "Kh", "Qh", "Jh", "10h", "9h", "8h", "7h", "6h", "5h", "4h", "3h", "2h",
"Ac", "Kc", "Qc", "Jc", "10c", "9c", "8c", "7c", "6c", "5c", "4c", "3c", "2c",
"Ad", "Kd", "Qd", "Jd", "10d", "9d", "8d", "7d", "6d", "5d", "4d", "3d", "2d"
};
}
public static List<Card> CreateCardDeck()
{
return CreateStringDeck().Select(x => new Card(x)).ToList();
}
}
}
|
966e7c998b68a6c8321c804d1cbdedd907ab2080
|
C#
|
AlexsanderJrAlves/Trabalho-Eleicao
|
/Eleicao/Eleicao/Valida.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Eleicao
{
public static class Valida
{
//Classe de validação, ela recebe os códigos dos vereadores com 4 digitos para saeber se é vereador ou não.
private static int ValidaV(int codigo)
{
int codigoVer = codigo;
try
{
if (codigoVer > 9999 || codigoVer < 0000)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}
if (codigoVer.ToString().Length != 4)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}
}
catch (Exception)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}
return codigoVer;
}
public static int getCodVer(int codigo)
{
return ValidaV(codigo);
}
//função para validar prefeito com dois digitos
private static int ValidaP(int codigo)
{
int codigoPre = codigo;
try
{
if (codigoPre >100 || codigoPre <00)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}if(codigoPre.ToString().Length != 2)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}
}
catch (Exception)
{
Console.WriteLine("Deu Erro, tente novamente!!!");
}
return codigoPre;
}
public static int getCodPre(int codigo)
{
return ValidaP(codigo);
}
}
}
|
3dcc6ab31a1073d6f2ab0f367454ad555ad3dae4
|
C#
|
vendolis/EDDiscovery
|
/EDDiscovery/Forms/SplashForm.cs
| 2.671875
| 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.Threading;
using System.Collections.Concurrent;
namespace EDDiscovery.Forms
{
public partial class SplashForm : Form
{
private Thread _thread;
public SplashForm()
{
_thread = Thread.CurrentThread;
InitializeComponent();
this.label_version.Text = "EDDiscovery " + System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[1].Split('=')[1];
}
[STAThread]
private static void _ShowForm(object param)
{
BlockingCollection<SplashForm> queue = (BlockingCollection<SplashForm>)param;
using (SplashForm splash = new SplashForm())
{
queue.Add(splash);
Application.Run(splash);
}
}
public void CloseForm()
{
if (!this.IsDisposed)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => this.CloseForm()));
}
else
{
this.Close();
Application.ExitThread();
}
}
}
public static SplashForm ShowAsync()
{
// Mono doesn't support having forms running on multiple threads.
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
return null;
}
BlockingCollection<SplashForm> queue = new BlockingCollection<SplashForm>();
Thread thread = new Thread(_ShowForm);
thread.Start(queue);
return queue.Take();
}
}
}
|
cf2bc3e7b4ddcb07e6ada900e7f63dc547ef469e
|
C#
|
mcculic/millarowframework
|
/src/Millarow.Rest/RestException.cs
| 2.65625
| 3
|
using System;
using System.Runtime.Serialization;
namespace Millarow.Rest
{
[Serializable]
public enum RestExceptionKind
{
Http,
Timeout,
Mapping,
Validation,
Configuration,
Serialization
}
[Serializable]
public class RestException : Exception
{
public RestException(RestExceptionKind kind)
{
Kind = kind;
}
public RestException(RestExceptionKind kind, string message)
: base(message)
{
Kind = kind;
}
public RestException(RestExceptionKind kind, string message, Exception inner)
: base(message, inner)
{
Kind = kind;
}
protected RestException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
Kind = (RestExceptionKind)info.GetValue(nameof(Kind), typeof(RestExceptionKind));
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(Kind), Kind);
base.GetObjectData(info, context);
}
public RestExceptionKind Kind { get; }
}
}
|
2cbce644664caa49e2fdd1955435c2fba05907ef
|
C#
|
mmendelson222/geocaching-fizzy
|
/Config.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fizzy
{
internal static class Config
{
private static string filepath;
internal static string FilePath
{
get
{
if (filepath == null)
GetEnv();
return filepath;
}
set
{
filepath = value;
SaveEnv();
}
}
const string ENV_SETTING = "gc-fizzy";
private static void GetEnv()
{
string s = System.Environment.GetEnvironmentVariable(ENV_SETTING, EnvironmentVariableTarget.User);
if (string.IsNullOrEmpty(s)) return;
filepath = s;
//string[] values = s.Split(new char[] { '|' });
//try
//{
// Application = string.IsNullOrEmpty(values[0]) ? null : values[0];
// DeploymentGroup = string.IsNullOrEmpty(values[1]) ? null : values[1];
// DeploymentID = string.IsNullOrEmpty(values[2]) ? null : values[2];
// DeploymentListLimit = string.IsNullOrEmpty(values[3]) ? 10 : int.Parse(values[3]);
//}
//catch { }
}
private static void SaveEnv()
{
new System.Threading.Thread(() =>
{
System.Threading.Thread.CurrentThread.IsBackground = true;
//string value = string.Format("{0}|{1}|{2}|{3}", Application, DeploymentGroup, DeploymentID, DeploymentListLimit);
string value = filepath;
System.Environment.SetEnvironmentVariable(ENV_SETTING, value, EnvironmentVariableTarget.User);
}).Start();
}
}
}
|
61ddac1f005c01fe3bd646038f1f3cf9492afd1a
|
C#
|
johann-gambolputty/robotbastards
|
/Source/Rb.Core/Sets/Interfaces/IObjectSetServiceMap.cs
| 2.828125
| 3
|
namespace Rb.Core.Sets.Interfaces
{
/// <summary>
/// Stores a set of services, accessible by type
/// </summary>
public interface IObjectSetServiceMap
{
/// <summary>
/// Adds a service to this set
/// </summary>
/// <param name="service">Service to add</param>
/// <exception cref="System.ArgumentNullException">Thrown if service is null</exception>
void AddService( IObjectSetService service );
/// <summary>
/// Removes a service from this set
/// </summary>
/// <param name="service">Service to remove</param>
/// <exception cref="System.ArgumentNullException">Thrown if service is null</exception>
void RemoveService( IObjectSetService service );
/// <summary>
/// Gets a service attached to this set, by its type. Throws an ArgumentException if the service does not exist
/// </summary>
/// <typeparam name="T">Type of service to retrieve</typeparam>
/// <returns>Returns the typed service</returns>
/// <exception cref="System.ArgumentException">Thrown if T is not a valid service</exception>
T SafeService<T>( ) where T : class;
/// <summary>
/// Gets a service attached to this set, by its type
/// </summary>
/// <typeparam name="T">Type of service to retrieve</typeparam>
/// <returns>Returns the typed service, or null if no such service exists</returns>
T Service<T>( ) where T : class;
}
}
|
8956d710fad35570e196e1601b8b6543587529e2
|
C#
|
Guizal/MSNotificaton
|
/src/Adapters/Web/Models/Notification/Notification.cs
| 2.53125
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
namespace DevPrime.Web.Models.Notification
{
public class Notification
{
public string Name { get; set; }
public string Email { get; set; }
public string Number { get; set; }
public IList<System.String> Params { get; set; }
public static Application.Services.Notification.Model.Notification FromWebToApplicationNotification(DevPrime.Web.Models.Notification.Notification source)
{
if(source is null)
return new Application.Services.Notification.Model.Notification();
Application.Services.Notification.Model.Notification model = new Application.Services.Notification.Model.Notification();
model.Name = source.Name;
model.Email = source.Email;
model.Number = source.Number;
model.Params = source.Params;
return model;
}
public static List<Application.Services.Notification.Model.Notification> FromWebToApplicationNotification(IList<DevPrime.Web.Models.Notification.Notification> sourceList)
{
List<Application.Services.Notification.Model.Notification> modelList = new List<Application.Services.Notification.Model.Notification>();
if(sourceList != null)
{
foreach(var source in sourceList)
{
Application.Services.Notification.Model.Notification model = new Application.Services.Notification.Model.Notification();
model.Name = source.Name;
model.Email = source.Email;
model.Number = source.Number;
model.Params = source.Params;
modelList.Add(model);
}
}
return modelList;
}
public virtual Application.Services.Notification.Model.Notification ToApplication()
{
var model = FromWebToApplicationNotification(this);
return model;
}
}
}
|
76d1c5da9750b1e7448f5f4603013de1bab2379d
|
C#
|
XuYan1988/MyWeChartTools
|
/WeChart/WZAutoEye/WZAutoEyeUtility/AttachData/AttachDataExtensions.cs
| 2.625
| 3
|
#region Using
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
#endregion
namespace WZAutoEye.WZAutoEyeMVC.Utility
{
public static class AttachDataExtensions
{
public static object GetAttachedData(this ICustomAttributeProvider provider, object key)
{
var attributes = (AttachDataAttribute[])provider.GetCustomAttributes(
typeof(AttachDataAttribute), false);
var obj = attributes.FirstOrDefault(a => a.Key.Equals(key));
if (obj == null)
throw new Exception("对象未添加AttachedData.");
return obj.Value;
}
public static T GetAttachedData<T>(this ICustomAttributeProvider provider, object key)
{
return (T)provider.GetAttachedData(key);
}
public static object GetAttachedData(this Enum value, object key)
{
return value.GetType().GetField(value.ToString()).GetAttachedData(key);
}
public static T GetAttachedData<T>(this Enum value, object key)
{
string typeKey = value.GetType().ToString();
string dataKey = value.ToString();
T data;
if (!AttachDataCache<T>.Current.ContainsKey(typeKey))
{
AttachDataCache<T>.Current[typeKey] = new Dictionary<string, T>();
data = (T)value.GetAttachedData(key);
AttachDataCache<T>.Current[typeKey][dataKey] = data;
}
if (!AttachDataCache<T>.Current[typeKey].ContainsKey(dataKey))
{
data = (T)value.GetAttachedData(key);
AttachDataCache<T>.Current[typeKey][dataKey] = data;
}
else
{
data = AttachDataCache<T>.Current[typeKey][dataKey];
}
return data;
}
}
}
|
64da69fdaa78aa400b5976d8202c8a179b0d0c88
|
C#
|
nationwidesy/WebFromC
|
/WebApplicationCWebForm/App_Code/SerializationDemo.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace WebApplicationCWebForm.App_Code
{
class SerializationDemo
{
public String output = string.Empty;
public SerializationDemo()
{
Person2 person = new Person2("Sophy", 12345);
IFormatter formatter = new BinaryFormatter();
using(FileStream stream = File.Create ("sophytestPersonal.data"))
{
formatter.Serialize(stream, person);
}
using (FileStream stream = File.OpenRead("sophytestPersonal.data"))
{
Person2 obj = (Person2)formatter.Deserialize(stream);
output = obj.ToString();
}
}
}
[Serializable] public class Person2
{
private string name;
private int id;
public Person2 (string nameVal, int idVal)
{
this.name = nameVal;
this.id = idVal;
}
public override string ToString()
{
return "name=" + this.name + " id=" + this.id;
}
}
}
|
fe041a4b08c6bdabfeae86ebf7f5a423b939d25f
|
C#
|
DevJHennessy/CSharp_Exercises
|
/CS_Exercise_16/CS_Exercise_16/Program.cs
| 3.765625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CS_Exercise_16
{
class Program
{
static void Main(string[] args)
{
//1.Create an interface called IQuittable and have it define a void method called
//Quit().
//2. Have your Employee class from the previous drill inherit that interface and
//implement the Quit() method in any way you choose.
//3. Use polymorphism to create an object of type IQuittable and call the Quit()
//method on it. Hint: an object can be of an interface type if it implements that
//specific interface.
IQuittable employee = new Employee();
employee.Quit();
}
}
}
|
1db753f923511aab44e78650f9825142a6a75d64
|
C#
|
dedeogluhu/Dotnet-demo
|
/OnlineShopping.ORM/DataAccessLayers/ProductDal.cs
| 2.84375
| 3
|
using OnlineShopping.Entity;
using OnlineShopping.ORM.Interfaces;
using OnlineShopping.ORM.Tools;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace OnlineShopping.ORM.DataAccessLayers
{
public class ProductDal : IEntityDal
{
public static bool Delete(int id)
{
SqlCommand sqlCommand = new SqlCommand("prc_Products_Delete", Utilities.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@Id", id);
return Utilities.ExecuteNonQuery(sqlCommand);
}
public static bool Insert(Product entity)
{
SqlCommand sqlCommand = new SqlCommand("prc_Products_Insert", Utilities.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@ProductName", entity.ProductName);
sqlCommand.Parameters.AddWithValue("@UnitPrice",entity.UnitPrice);
sqlCommand.Parameters.AddWithValue("@StockAmount", entity.StockAmount);
sqlCommand.Parameters.AddWithValue("@SellerId", entity.SellerId);
return Utilities.ExecuteNonQuery(sqlCommand);
}
public static void Delete(object dataBoundItem)
{
throw new NotImplementedException();
}
public static List<Product> Select()
{
SqlCommand sqlCommand = new SqlCommand("prc_Products_Select", Utilities.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
List<Product> products = new List<Product>();
Utilities.OpenConnection(sqlCommand);
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
Product product = new Product
{
Id = Convert.ToInt32(sqlDataReader["Id"]),
ProductName = sqlDataReader["ProductName"].ToString(),
SellerId = Convert.ToInt32(sqlDataReader["SellerId"]),
UnitPrice = Convert.ToDecimal(sqlDataReader["UnitPrice"]),
StockAmount = Convert.ToInt32(sqlDataReader["StockAmount"]),
isActive = Convert.ToBoolean(sqlDataReader["isActive"])
};
products.Add(product);
}
Utilities.CloseConnection(sqlCommand);
return products;
}
public static bool Update(Product entity)
{
SqlCommand sqlCommand = new SqlCommand("prc_Products_Update", Utilities.Connection);
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("@Id", entity.Id);
sqlCommand.Parameters.AddWithValue("@ProductName", entity.ProductName);
sqlCommand.Parameters.AddWithValue("@SellerId", entity.SellerId);
sqlCommand.Parameters.AddWithValue("@UnitPrice", entity.UnitPrice);
sqlCommand.Parameters.AddWithValue("@StockAmount", entity.StockAmount);
return Utilities.ExecuteNonQuery(sqlCommand);
}
}
}
|
31d81d3c5c431a83b3a30bf64b0d86165005bfee
|
C#
|
ronnieholm/Backend-web-programming-course-spring-2015
|
/Source/Exercises/Exercise31/StudentCollectionSolution.cs
| 3.34375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exercises.Exercise31
{
class RunnerSolution
{
public void Run()
{
StudentCollectionSolution students = new StudentCollectionSolution();
Student anna = new Student(12, "Anna");
Student betty = new Student(338, "Betty");
Student carl = new Student(92, "Carl");
anna.AddTestResult("English", 85);
anna.AddTestResult("Math", 70);
anna.AddTestResult("Biology", 90);
anna.AddTestResult("French", 52);
betty.AddTestResult("English", 77);
betty.AddTestResult("Math", 82);
betty.AddTestResult("Chemistry", 65);
betty.AddTestResult("French", 41);
carl.AddTestResult("English", 55);
carl.AddTestResult("Math", 48);
carl.AddTestResult("Biology", 70);
carl.AddTestResult("French", 38);
students.AddStudent(anna.GetId(), anna);
students.AddStudent(betty.GetId(), betty);
students.AddStudent(carl.GetId(), carl);
// does output match you expectations?
Console.WriteLine(students.GetStudentCount());
Console.WriteLine(students.GetStudent(12).GetName());
Console.WriteLine(students.GetStudent(338).GetName());
Console.WriteLine(students.GetStudent(92).GetName());
Console.WriteLine(students.GetAverageForStudent(12));
Console.WriteLine(students.GetAverageForStudent(338));
Console.WriteLine(students.GetAverageForStudent(92));
Console.WriteLine(students.GetAverageForStudent(120));
Console.WriteLine(students.GetTotalAverage());
}
}
class StudentCollectionSolution
{
private Dictionary<int, Student> _students;
public StudentCollectionSolution()
{
_students = new Dictionary<int, Student>();
}
// returns number of students in collection
public int GetStudentCount()
{
// add code here
return _students.Count;
}
// adds student to collections
public void AddStudent(int id, Student student)
{
// add code here
_students.Add(id, student);
}
// given a student id, returns student with that id.
// If no student exists with id, return null
public Student GetStudent(int id)
{
// add code here
if (_students.ContainsKey(id))
{
return _students[id];
}
else
{
return null;
}
}
// given a student id, return the average score for student with id.
// If no student exists with the given id, return 0.
public int GetAverageForStudent(int id)
{
// add code here
if (_students.ContainsKey(id))
{
return _students[id].GetScoreAverage();
}
else
{
return 0;
}
}
// calculate total test score average for all students.
// Tip: use GetAllStudentIds and a loop.
public int GetTotalAverage()
{
// add code here
List<int> ids = GetAllStudentIds();
int sum = 0;
foreach (int id in ids)
{
sum += GetAverageForStudent(id);
}
return sum / ids.Count;
}
// returns all ids of students in collections (leave as is)
public List<int> GetAllStudentIds()
{
// a bit of black magic
return new List<int>(_students.Keys.ToArray());
}
}
}
|
1b2b925b5c8571cbfe8d379ec60aa8f0b904ef52
|
C#
|
subbob/TravCharGen_CSharp
|
/Debug.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyLib
{
public class Debug
{
private static MyLib.cPrint OutFile = new MyLib.cPrint();
private static bool DebugMode = true;
public void PrintMsg (string msg)
{
if (DebugMode)
{
OutFile.PrintLine("\n\t***\t" + msg + "\t***\n");
}
}
public bool Mode()
{
return DebugMode;
}
public void ToggleMode()
{
DebugMode = !DebugMode;
}
public void DebugOn()
{
DebugMode = true;
}
public void DebugOff()
{
DebugMode = false;
}
}
}
|
74b0cb70bb23b713a018d1da2fcf030abe9c0d11
|
C#
|
SebastianDominguezC/Data-Persistence-Project
|
/Assets/Scripts/Persistance.cs
| 2.78125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class Persistance : MonoBehaviour
{
public static Persistance Instance;
public string Name;
public HighScore HS;
private void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
public void ChangeName(string newName)
{
Name = newName;
}
[System.Serializable]
public class HighScore
{
public string name;
public int score;
}
public void AddHighScore(int score, string name)
{
string path = Application.persistentDataPath + "/highscores.json";
if (File.Exists(path))
{
string json = File.ReadAllText(path);
HighScore highScore = JsonUtility.FromJson<HighScore>(json);
if (score > highScore.score)
{
highScore.score = score;
highScore.name = name;
HS = highScore;
WriteHighScore(name, score);
}
}
}
public void WriteHighScore(string name, int score)
{
HighScore hs = new HighScore
{
name = name,
score = score,
};
string path = Application.persistentDataPath + "/highscores.json";
string json = JsonUtility.ToJson(hs);
File.WriteAllText(path, json);
}
public void LoadHighScore()
{
string path = Application.persistentDataPath + "/highscores.json";
if (File.Exists(path))
{
string json = File.ReadAllText(path);
HighScore highScore = JsonUtility.FromJson<HighScore>(json);
HS = highScore;
}
else
{
WriteHighScore("", 0);
}
}
}
|
8232666c4c9f2b5ccbacad24ac678c0ca641d777
|
C#
|
davidparker83686/keepr
|
/keeprserver/Services/VaultsService.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using keepr.Models;
using keepr.Repositories_;
namespace keepr.Services
{
public class VaultsService
{
private readonly VaultsRepository _vaultsRepository;
private readonly VaultKeepsRepository _vaultKeepsRepository;
public VaultsService(VaultsRepository vaultsRepository, VaultKeepsRepository vaultKeepsRepository)
{
_vaultsRepository = vaultsRepository;
_vaultKeepsRepository = vaultKeepsRepository;
}
// -----------------------------------------------------------------------------------------------------
internal IEnumerable<Vault> GetAll()
{
return _vaultsRepository.GetAll();
}
// -----------------------------------------------------------------------------------------------------
internal IEnumerable<Vault> GetByCreatorId(string id)
{
throw new NotImplementedException();
}
// -----------------------------------------------------------------------------------------------------
internal Vault Create(Vault newVault)
{
Vault vaults = _vaultsRepository.Create(newVault);
return vaults;
}
// -----------------------------------------------------------------------------------------------------
internal IEnumerable<VaultKeepViewModel> GetKeepByVault(int id)
{
return _vaultKeepsRepository.GetKeepByVault(id);
}
// -----------------------------------------------------------------------------------------------------
internal Vault GetById(int id)
{
Vault vault = _vaultsRepository.GetById(id);
if (vault == null)
{
throw new Exception("Invalid Vault Id");
}
return (Vault)vault;
}
// internal void Delete(int id, string creatorId)
// {
// Car car = GetById(id);
// if (car.CreatorId != creatorId)
// {
// throw new Exception("You cannot delete another users Car");
// }
// if (!_repo.Delete(id))
// {
// throw new Exception("Something has gone terribly wrong");
// };
// -----------------------------------------------------------------------------------------------------
// internal IEnumerable<Vault> GetVaultByProfile(string id)
// {
// return _vaultsRepository.GetVaultByProfile(id);
// }
internal IEnumerable<Vault> GetVaultByProfile(string id, string userId)
{
if (id != userId)
{
return _vaultsRepository.GetVaultByProfile(id).ToList().FindAll(v => v.IsPrivate == false);
}
return _vaultsRepository.GetVaultByProfile(id);
}
// -----------------------------------------------------------------------------------------------------
internal void Delete(int apple, string id2)
{
Vault vault = GetById(apple);
if (!_vaultsRepository.Delete(apple))
{
throw new Exception("Something has gone terribly wrong");
}
}
// internal Vault GetById(string id)
// {
// throw new NotImplementedException();
// }
// -----------------------------------------------------------------------------------------------------
internal Vault Update(Vault update)
{
Vault original = GetById(update.Id);
original.Name = update.Name.Length > 0 ? update.Name : original.Name;
original.Description = update.Description.Length > 0 ? update.Description : original.Description;
original.IsPrivate = update.IsPrivate != update.IsPrivate ? update.IsPrivate : original.IsPrivate;
if (_vaultsRepository.Update(original))
{
return original;
}
throw new Exception("Something Went Wrong???");
}
}
}
|
ec0ba677ab3cdaf84e8d7d29132e08ccab1149bb
|
C#
|
erinaldo/Siav
|
/SVC_BLL/SubGrupoBLL.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using One.Dal;
namespace One.Bll
{
public class SubGrupoBLL
{
public int sg_codigo { get; set; }
public String sg_descricao { get; set; }
public int sg_grupo { get; set; }
SubGrupoDAL objDAL = null;
public SubGrupoBLL()
{ }
public void limpar()
{
try
{
this.sg_codigo = 0;
this.sg_descricao = null;
this.sg_grupo = 0;
}
catch (Exception)
{
throw;
}
}
public void inserir()
{
try
{
objDAL = new SubGrupoDAL();
objDAL.inserir(this.sg_descricao, this.sg_grupo);
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void alterar()
{
try
{
objDAL = new SubGrupoDAL();
objDAL.alterar(this.sg_codigo, this.sg_descricao, this.sg_grupo);
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void excluir()
{
try
{
objDAL = new SubGrupoDAL();
objDAL.excluir(this.sg_codigo);
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void localizar()
{
try
{
objDAL = new SubGrupoDAL();
this.sg_codigo = objDAL.localizar(this.sg_codigo);
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void localizar(String descricao, String atributo)
{
try
{
DataTable tab;
objDAL = new SubGrupoDAL();
tab = objDAL.localizar(descricao, atributo);
if (tab.Rows.Count > 0)
{
this.sg_codigo = int.Parse(tab.Rows[0]["sg_codigo"].ToString());
this.sg_descricao = tab.Rows[0]["sg_descricao"].ToString();
this.sg_grupo = int.Parse(tab.Rows[0]["sg_grupo"].ToString());
}
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void localizarLeave(String descricao, String atributo)
{
try
{
DataTable tab;
objDAL = new SubGrupoDAL();
tab = objDAL.localizarLeave(descricao, atributo);
if (tab.Rows.Count > 0)
{
this.sg_codigo = int.Parse(tab.Rows[0]["sg_codigo"].ToString());
this.sg_descricao = tab.Rows[0]["sg_descricao"].ToString();
this.sg_grupo = int.Parse(tab.Rows[0]["sg_grupo"].ToString());
}
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public DataTable localizarComRetorno(String descricao, String atributo)
{
try
{
DataTable tab;
objDAL = new SubGrupoDAL();
tab = objDAL.localizar(descricao, atributo);
objDAL = null;
return tab;
}
catch (Exception)
{
throw;
}
}
public DataTable localizarEmTudo(String descricao)
{
try
{
DataTable tab;
objDAL = new SubGrupoDAL();
tab = objDAL.localizarEmTudo(descricao);
objDAL = null;
return tab;
}
catch (Exception)
{
throw;
}
}
public void localizarPrimeiroUltimo(String descricao)
{
try
{
DataTable tab = null;
int codigo = 0;
objDAL = new SubGrupoDAL();
tab = objDAL.localizarPrimeiroUltimo(descricao);
if (tab.Rows.Count > 0)
int.TryParse(tab.Rows[0][0].ToString(), out codigo);
this.sg_codigo = codigo;
objDAL = null;
}
catch (Exception)
{
throw;
}
}
public void localizarProxAnterior(String descricao, int codigo)
{
try
{
DataTable tab = null;
objDAL = new SubGrupoDAL();
tab = objDAL.localizarProxAnterior(descricao, codigo);
if (tab.Rows.Count > 0)
this.sg_codigo = int.Parse(tab.Rows[0][0].ToString());
objDAL = null;
}
catch (Exception)
{
throw;
}
}
}
}
|
8c09657c41c64062a4a1250ae89705e67d6a7573
|
C#
|
1stResponder/fresh
|
/Fresh.Global/IconConfig.cs
| 2.6875
| 3
|
using Fresh.Global.IconHelpers;
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
namespace Fresh.Global
{
public static class IconConfig
{
//TODO: put in the web config file
static string IconFileName = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/IconFiles.xml");
static FreshIcons mIcons;
public static FreshIcons Icons
{
get
{
if (mIcons == null)
{
try
{
XmlSerializer xs = new XmlSerializer(typeof(FreshIcons));
using (FileStream fileStream = new FileStream(IconFileName, FileMode.Open))
{
mIcons = (FreshIcons)xs.Deserialize(fileStream);
}
}
catch (Exception Ex)
{
DEUtilities.LogMessage(Ex.ToString(), DEUtilities.LogLevel.Error);
}
}
return mIcons;
}
set
{
mIcons = value;
if (mIcons != null)
{
XmlSerializer xs = new XmlSerializer(typeof(FreshIcons));
using (TextWriter tw = new StreamWriter(IconFileName))
{
xs.Serialize(tw, mIcons);
}
}
}
}
// parses sets from Xml file
// calls buildGroup to handle groups and icons
private static void buildSets(string file)
{
XmlReader reader = XmlReader.Create(file);
reader.ReadStartElement("FreshIcons");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "IconSet")
{
IconSet set = new IconSet();
set.KindofSet = reader.GetAttribute(0);
set.Groups = buildGroup(file, set.KindofSet);
mIcons.Sets.Add(set);
}
}
}
// parses groups their associated files for given IconSet
private static List<IconGroup> buildGroup(string file, string setname)
{
List<IconGroup> grouplist = new List<IconGroup>();
XmlReader reader = XmlReader.Create(file);
reader.ReadStartElement("FreshIcons");
Boolean found = false;
while(reader.Read())
{
// set reader location to this group's IconSet
if (reader.Name == "IconSet" && reader.GetAttribute(0) == setname && reader.IsStartElement())
{
found = true;
break;
}
else reader.Skip(); // skip over children of current node
}
// proper IconSet found in file
if (found)
{
// continue reading
while (reader.Read())
{
if(reader.Name == "IconGroup")
{
/* Set KindofGroup */
string KindofGroup = reader.GetAttribute(0);
/* Set RootFolder */
string RootFolder;
// next element should be RootFolder, throw exception otherwise
if (reader.Read())
{
if (reader.Name != "RootFolder") throw new XmlException("Invalid Xml format.");
RootFolder = reader.ReadContentAsString();
}
else throw new XmlException("Invalid Xml format.");
/* Set Filenames */
List<string> Filenames = new List<string>();
// next element should be Icons, throw exception otherwise
if (reader.Read())
{
if (reader.Name != "Icons") throw new XmlException("Invalid Xml format.");
// advance reader; in most cases will now point to first icon file; includes check for invalid file structure
if (!reader.Read()) throw new XmlException("Invalid Xml format.");
while(reader.Name == "Icon")
{
Filenames.Add(reader.ReadContentAsString());
if (!reader.Read()) throw new XmlException("Invalid Xml format.");
}
}
else throw new XmlException("Invalid Xml format.");
/* Add IconGroup to list */
grouplist.Add(new IconGroup(KindofGroup, RootFolder, Filenames));
}
}
}
// did not find requested group - throw error
else
{
throw new XmlException("Requested IconGroup not found.");
}
return grouplist;
}
}
}
|
6cea0bb7c23ab8c845e98838814c580d7023238f
|
C#
|
hansenjacobs/Chatroom
|
/Server/Client.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Server
{
class Client : IRecipient
{
NetworkStream stream;
TcpClient client;
public Client(NetworkStream Stream, TcpClient Client, Dictionary<string, Chatroom> chatrooms, string userName)
{
stream = Stream;
client = Client;
UserName = userName;
Chatrooms = chatrooms;
}
private string ListChatrooms
{
get
{
string output = "";
foreach (KeyValuePair<string, Chatroom> chatroom in Chatrooms)
{
output += chatroom.Key.ToString() + "\n";
}
return output.Trim();
}
}
public Chatroom CurrentChatroom { get; set; }
public Dictionary<string, Chatroom> Chatrooms { get; set; }
public string UserName { get; private set; }
public void ChatroomMenu()
{
Send("What chatroom would you like to join?");
string input = "";
do
{
input = GetUserInput(ListChatrooms + "\n");
} while (!Chatrooms.ContainsKey(input));
ChangeChatroom(Chatrooms[input]);
}
public void ChatroomMenu(string input)
{
if (!Chatrooms.ContainsKey(input))
{
Send("What chatroom would you like to join?");
do
{
input = GetUserInput(ListChatrooms);
} while (!Chatrooms.ContainsKey(input));
}
ChangeChatroom(Chatrooms[input]);
}
public void ChangeChatroom(Chatroom chatroom)
{
if(CurrentChatroom != null)
{
CurrentChatroom.RemoveUser(UserName);
}
CurrentChatroom = chatroom;
Send($"Welcome to the {CurrentChatroom.Name} chatroom. To change rooms enter '>>' or enter '>>' + the name of the room, for example, '>>Main' to move to the Main chatroom.\n");
CurrentChatroom.AddUser(UserName, this);
}
public void DeliverMessage(Message message)
{
byte[] encodedMessage;
if (message.Sender != null)
{
encodedMessage = Encoding.ASCII.GetBytes($"{message.ReceivedDateTime.ToString("G")} {message.Sender.UserName} >> {message.Body}");
}
else
{
encodedMessage = Encoding.ASCII.GetBytes($"{message.ReceivedDateTime.ToString("G")} {message.Body}");
}
stream.Write(encodedMessage, 0, encodedMessage.Count());
}
public string GetUserInput(string message)
{
Send(message);
byte[] recievedMessage = new byte[5000];
stream.Read(recievedMessage, 0, recievedMessage.Length);
return Encoding.ASCII.GetString(recievedMessage).Trim('\0');
}
public string Receive()
{
try
{
while (true)
{
byte[] recievedMessage = new byte[5000];
stream.Read(recievedMessage, 0, recievedMessage.Length);
string messageString = Encoding.ASCII.GetString(recievedMessage);
if(messageString.Substring(0, 2) != ">>")
{
CurrentChatroom.EnqueueMessage(new Message(this, recievedMessage, CurrentChatroom.Name));
}
else
{
return messageString.Trim().Trim('\0');
}
}
}
catch (IOException)
{
Server.CloseClient(this);
return "";
}
}
public void Send(string messageString)
{
byte[] message = Encoding.ASCII.GetBytes(messageString);
stream.Write(message, 0, message.Count());
}
public void SetUser(Dictionary<string, Client> clients)
{
bool usernameSet = false;
do
{
string input = GetUserInput("Please enter your username:");
if (!clients.ContainsKey(input))
{
string oldUserName = UserName;
UserName = input;
clients.Remove(oldUserName);
clients.Add(UserName, this);
usernameSet = true;
}
else
{
Send("That username is already in use, please try again.");
}
} while (!usernameSet);
}
public void Start()
{
Send(UserName + " welcome to the chat server.\n");
ChatroomMenu();
string input = "";
do
{
input = Receive();
if(input.Length >= 2 && input.Substring(0, 2) == ">>")
{
ChatroomMenu(input.Substring(2));
}
} while (input != "");
CurrentChatroom.RemoveUser(UserName);
}
}
}
|
56d170a99d7ed2a06acadc9af325dfa77d01dc73
|
C#
|
PetrovPetar5/Databases-MSSQL-EntityFramework-SoftUni-Problems
|
/Entity Framework Core/ADO.NET/PrintAllMinionNames/Program.cs
| 3.390625
| 3
|
namespace PrintAllMinionNames
{
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
const string connectionString = @"Server=.;Database=MinionsDB;Integrated Security=true;";
List<string> minions = new List<string>();
using var connection = new SqlConnection(connectionString);
connection.Open();
var showAllMinionsQuery = @"SELECT Name FROM Minions";
using var showMinions = new SqlCommand(showAllMinionsQuery, connection);
using var result = showMinions.ExecuteReader();
while (result.Read())
{
minions.Add((string)result[0]);
}
var counter = 0;
for (int i = 0; i < minions.Count / 2; i++)
{
Console.WriteLine(minions[i]);
Console.WriteLine(minions[minions.Count - 1 - counter]);
counter++;
}
if (minions.Count % 2 != 0)
{
Console.WriteLine(minions[minions.Count / 2]);
}
}
}
}
|
ffde324ac937671c5551e3231748e54198cf4fcb
|
C#
|
pinarbulbul/DowntimeAlerter
|
/DowntimeAlerter.Infrastructure/BackgroundJob/HealthCheckJob.cs
| 2.578125
| 3
|
using DowntimeAlerter.Application.Notifications;
using DowntimeAlerter.EntityFrameworkCore.TargetDb;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace DowntimeAlerter.Infrastructure.BackgroundJob
{
public class HealthCheckJob: IHealthCheckJob
{
private readonly TargetDbContext _context;
private readonly IHttpClientFactory _clientFactory;
private readonly INotificationSender _notificationSender;
public HealthCheckJob(TargetDbContext context, IHttpClientFactory clientFactory ,
INotificationSender notificationSender)
{
this._context = context;
_clientFactory = clientFactory;
_notificationSender = notificationSender;
}
public async Task CheckHealth(int targetId, string userMail)
{
var target = await _context.Target.FindAsync(targetId);
var check = new Domain.Entities.HealthCheckResult
{
TargetId = targetId,
StatusCode = 0,
ExecutionTime = DateTime.UtcNow,
Result = target == null ? Domain.Enums.HealthCheckResultEnum.NotFound : Domain.Enums.HealthCheckResultEnum.Error
};
try
{
if (target != null)
{
using (var client = _clientFactory.CreateClient())
{
using (var response = await client.GetAsync(target.Url))
{
check.StatusCode = (int)response.StatusCode;
check.Result = response.IsSuccessStatusCode ? Domain.Enums.HealthCheckResultEnum.Success : Domain.Enums.HealthCheckResultEnum.UnSuccess;
if (!response.IsSuccessStatusCode)
{
var subject = $"Downtime Alerter : {target.Name} service is down";
var message = $"<p>{target.Url} could not be reached at {check.ExecutionTime}</p>";
await _notificationSender.SendNotificationAsync(userMail, subject, message);
}
}
}
}
}
catch (Exception ex)
{
var subject = $"Downtime Alerter : {target.Name} is not reached";
var message = $"<p>Error received during check url {target.Url} at {check.ExecutionTime}</p><p>{ex.Message}</p> ";
await _notificationSender.SendNotificationAsync(userMail, subject, message);
throw new Exception(ex.Message, ex);
}
finally
{
await _context.HealthCheckResult.AddAsync(check);
await _context.SaveChangesAsync();
}
}
}
}
|
008e3d1b8fc3c5d17291005514e852f4f3b0654e
|
C#
|
limonana/Recommendation_Systems_Course
|
/3/ProbabilityForest/DB.cs
| 3.46875
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProbabilityForest
{
class DB
{
public void LoadPart(string fileName, int lineCount)
{
var reader = new StreamReader(fileName);
for (int i = 0; i < lineCount; i++)
{
addLine(reader.ReadLine());
}
reader.Close();
}
public void LoadAll(string fileName)
{
var lines = File.ReadLines(fileName);
foreach (var line in lines)
{
addLine(line);
}
}
Dictionary<string, HashSet<string>> usersTOItems = new Dictionary<string, HashSet<string>>();
public void Add(string user, string item)
{
if (!usersTOItems.ContainsKey(user))
usersTOItems.Add(user, new HashSet<string>());
usersTOItems[user].Add(item);
}
public IEnumerable<string> GetAllUsers()
{
return usersTOItems.Keys;
}
public IEnumerable<string> GetAllItems()
{
return usersTOItems.SelectMany(x => x.Value).Distinct();
}
public bool isUsing(string user, string item)
{
return usersTOItems[user].Contains(item);
}
public int NumOfUsers()
{
return usersTOItems.Keys.Count;
}
public IEnumerable<string> ItemsOf(string user)
{
return usersTOItems[user];
}
public IEnumerable<string> ItemsOf(IEnumerable<string> users)
{
return users.SelectMany(usr => ItemsOf(usr));
}
public IEnumerable<string> UsersOf(string item)
{
return usersTOItems.Keys.Where(usr => isUsing(usr, item));
}
private void addLine(String line)
{
var parts = line.Split('\t');
for (int i = 1; i < parts.Length; i+=2)
{
Add(parts[0], parts[i].Split(',')[0]);
}
}
}
}
|
922500a881a79a681ab9f1879a9a91eed2cc8011
|
C#
|
ppedvAG/190402_Xamarin_BGH
|
/DatenSpeichernUndLaden/DatenSpeichernUndLaden/DatenSpeichernUndLaden/RESTPage.xaml.cs
| 2.859375
| 3
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace DatenSpeichernUndLaden
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class RESTPage : ContentPage
{
public RESTPage()
{
InitializeComponent();
}
private async void ListView_Refreshing(object sender, EventArgs e)
{
// 1) Webseite als string herunterladen
// 2) Daten(json-string) Deserialisieren
// 3) Daten in die ListView eintragen
using (HttpClient client = new HttpClient())
{
// Option in VisualStudio "Enable Single-Click URL Navigation" - Abdrehen
string json = await client.GetStringAsync("https://jsonplaceholder.typicode.com/todos");
listViewToDo.ItemsSource = JsonConvert.DeserializeObject<List<ToDoItem>>(json);
} // Sobald wir den using-block verlassen, wird der HTTPClient für uns ordnungsgemäß geschlossen
listViewToDo.EndRefresh();
}
}
}
|
3f0b47311bd69964038e7b8ef74f20e5a2c9f456
|
C#
|
chengming0916/SamplePrism
|
/SamplePrism.Presentation.Common/Message.cs
| 2.90625
| 3
|
namespace SamplePrism.Presentation.Common
{
public class Message
{
public Message(string rawMessage)
{
Key = rawMessage.Substring(0, rawMessage.IndexOf(':'));
var message = rawMessage.Split(':')[1];
string command = message.Substring(1, message.IndexOf(">") - 1);
string data = message.Substring(message.IndexOf(">") + 1);
Command = command;
Data = data;
}
public string Key { get; set; }
public string Command { get; set; }
public string Data { get; set; }
public int DataCount { get { return Data.Split('#').Length; } }
public string GetData(int index)
{
string result = "";
if (index < DataCount)
{
result = Data.Split('#')[index];
}
return result;
}
}
}
|
00354579f4038c2b78d7b892bbb48ce59269475e
|
C#
|
evgenyviyachev/CSharp-Advanced
|
/2. Sets and Dictionaries/SetsDictionariesEx/Problem 11/LogsAggregator.cs
| 3.203125
| 3
|
using System;
using System.Collections.Generic;
namespace Problem_11
{
class LogsAggregator
{
static void Main()
{
int lines = int.Parse(Console.ReadLine());
SortedDictionary<string, SortedSet<string>> usernameIPs = new SortedDictionary<string, SortedSet<string>>();
Dictionary<string, int> usernameDuration = new Dictionary<string, int>();
for (int i = 0; i < lines; i++)
{
string[] data = Console.ReadLine().Split(' ');
string IP = data[0];
string username = data[1];
int duration = int.Parse(data[2]);
if (!usernameIPs.ContainsKey(username))
{
usernameIPs.Add(username, new SortedSet<string>());
usernameDuration.Add(username, 0);
}
usernameIPs[username].Add(IP);
usernameDuration[username] += duration;
}
foreach (var user in usernameIPs.Keys)
{
Console.Write($"{user}: {usernameDuration[user]} [");
Console.Write(string.Join(", ", usernameIPs[user]));
Console.WriteLine("]");
}
}
}
}
|
8765a019ad419750ef62aa4cd0bec2f1feefd348
|
C#
|
gregfield/IN710-fielgm2
|
/Week 7/PredicateDelegate/PredicateDelegate/Form1.cs
| 3.328125
| 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 PredicateDelegate
{
public partial class Form1 : Form
{
List<int> randomNumbers;
public Form1()
{
InitializeComponent();
randomNumbers = new List<int>();
}
private void generateRandoms_Click(object sender, EventArgs e)
{
randomNumbers.Clear();
listBox1.Items.Clear();
Random randNumbers = new Random();
for(int i = 0; i < 100; i++)
{
randomNumbers.Add(randNumbers.Next(100));
}
foreach(int currentInt in randomNumbers)
{
listBox1.Items.Add(currentInt.ToString());
}
}
private void selectEvens_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
Predicate<int> isEvenPredicate = new Predicate<int>(isEven);
List<int> evens = randomNumbers.FindAll(isEvenPredicate);
foreach (int currentInt in evens)
{
listBox2.Items.Add(currentInt);
}
}
private void selectLessThan10_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
Predicate<int> isLessThanTenPredicate = new Predicate<int>(isLessThan10);
List<int> lessThanTen = randomNumbers.FindAll(isLessThanTenPredicate);
foreach (int currentInt in lessThanTen)
{
listBox2.Items.Add(currentInt);
}
}
private bool isEven(int inputInteger)
{
bool isAnEvenNumber = ((inputInteger % 2) == 0);
return isAnEvenNumber;
}
private bool isLessThan10(int inputInteger)
{
bool isLessThan = false;
if(inputInteger < 10)
{
isLessThan = true;
}
return isLessThan;
}
}
}
|
87d727cc7671f107c6c8ba559d15c1f8df2754dc
|
C#
|
xamarin/java.interop
|
/tools/param-name-importer/JavaApiParameterNamesExporter.cs
| 2.75
| 3
|
using System;
using System.IO;
using System.Linq;
using System.Xml;
using Xamarin.Android.Tools.ApiXmlAdjuster;
namespace Xamarin.Android.Tools.ApiXmlAdjuster
{
public static class JavaApiParameterNamesExporter
{
public static void WriteParameterNamesXml (this JavaApi api, string file)
{
using (var xw = XmlWriter.Create (file, new XmlWriterSettings { Indent = true }))
WriteParameterNamesXml (api, xw);
}
public static void WriteParameterNamesXml (this JavaApi api, XmlWriter writer)
{
writer.WriteStartElement ("parameter-names");
Action<JavaTypeParameters> writeTypeParameters = tps => {
if (tps != null && tps.TypeParameters.Any ()) {
writer.WriteStartElement ("type-parameters");
foreach (var gt in tps.TypeParameters) {
writer.WriteStartElement ("type-parameter");
writer.WriteAttributeString ("name", gt.Name);
// no need to supply constraints.
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
};
foreach (var package in api.AllPackages.OrderBy (p => p.Name)) {
writer.WriteStartElement ("package");
writer.WriteAttributeString ("name", package.Name);
foreach (var type in package.AllTypes.OrderBy (t => t.Name)) {
if (!type.Members.OfType<JavaMethodBase> ().Any (m => m.Parameters.Any ()))
continue; // we care only about types that has any methods that have parameters.
writer.WriteStartElement (type is JavaClass ? "class" : "interface");
writer.WriteAttributeString ("name", type.Name);
writeTypeParameters (type.TypeParameters);
// we care only about methods that have parameters.
foreach (var mb in type.Members.OfType<JavaMethodBase> ().Where (m => m.Parameters.Any ())) {
if (mb is JavaConstructor)
writer.WriteStartElement ("constructor");
else {
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", mb.Name);
}
writeTypeParameters (mb.TypeParameters);
foreach (var para in mb.Parameters) {
writer.WriteStartElement ("parameter");
// For possible generic instances in parameter type, we replace all ", " with "," to ease parsing.
writer.WriteAttributeString ("type", para.Type.Replace (", ", ","));
writer.WriteAttributeString ("name", para.Name);
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
writer.WriteEndElement ();
}
/*
* The Text Format is:
*
* package {packagename}
* ;---------------------------------------
* interface {interfacename}{optional_type_parameters} -or-
* class {classname}{optional_type_parameters}
* {optional_type_parameters}{methodname}({parameters})
*
* Anything after ; is treated as comment.
*
* optional_type_parameters: "" -or- "<A,B,C>" (no constraints allowed)
* parameters: type1 p0, type2 p1 (pairs of {type} {name}, joined by ", ")
*
* It is with strict indentations. two spaces for types, four spaces for methods.
*
* Constructors are named as "#ctor".
*
* Commas are used by both parameter types and parameter separators,
* but only parameter separators can be followed by a whitespace.
* It is useful when writing text parsers for this format.
*
* Type names may contain whitespaces in case it is with generic constraints (e.g. "? extends FooBar"),
* so when parsing a parameter type-name pair, the only trustworthy whitespace for tokenizing name is the *last* one.
*/
public static void WriteParameterNamesText (this JavaApi api, string file)
{
using (var sw = new StreamWriter (file))
WriteParameterNamesText (api, sw);
}
public static void WriteParameterNamesText (this JavaApi api, TextWriter writer)
{
Action<string,JavaTypeParameters> writeTypeParameters = (indent, tps) => {
if (tps != null && tps.TypeParameters.Any ())
writer.Write ($"{indent}<{string.Join (",", tps.TypeParameters.Select (p => p.Name))}>");
};
foreach (var package in api.AllPackages.OrderBy (p => p.Name)) {
writer.WriteLine ();
writer.WriteLine ($"package {package.Name}");
writer.WriteLine (";---------------------------------------");
foreach (var type in package.AllTypes.OrderBy (t => t.Name)) {
if (!type.Members.OfType<JavaMethodBase> ().Any (m => m.Parameters.Any ()))
continue; // we care only about types that has any methods that have parameters.
writer.Write (type is JavaClass ? " class " : " interface ");
writer.Write (type.Name);
writeTypeParameters ("", type.TypeParameters);
writer.WriteLine ();
// we care only about methods that have parameters.
foreach (var mb in type.Members.OfType<JavaMethodBase> ().Where (m => m.Parameters.Any ())) {
writer.Write (" ");
writeTypeParameters (" ", mb.TypeParameters);
var name = mb is JavaConstructor ? "#ctor" : mb.Name;
// For possible generic instances in parameter type, we replace all ", " with "," to ease parsing.
writer.WriteLine ($" {name}({string.Join (", ", mb.Parameters.Select (p => p.Type.Replace (", ", ",") + ' ' + p.Name))})");
}
}
}
}
}
}
|
b25cba1caf79f0731a74d86701bb42bf1a2c013a
|
C#
|
SergeyDushkin/TechFactory
|
/TF/src/TF.DAL/UserRoleRepository.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using TF.DAL.Query;
using TF.Data.Systems.Security;
namespace TF.DAL
{
public class UserRoleRepository : IUserRoleRepository
{
private readonly NoodleDbContext context;
public UserRoleRepository(NoodleDbContext context)
{
this.context = context;
}
public void Delete(Guid id)
{
using (var connection = context.CreateConnection())
{
connection.Execute(UserRoleQuery.Delete(id));
}
}
public IEnumerable<UserRole> GetAll()
{
using (var connection = context.CreateConnection())
{
return connection.Query<UserRole>(UserRoleQuery.All());
}
}
public UserRole GetById(Guid id)
{
using (var connection = context.CreateConnection())
{
return connection.Query<UserRole>(UserRoleQuery.ById(id)).SingleOrDefault();
}
}
public UserRole Update(UserRole userrole)
{
using (var connection = context.CreateConnection())
{
connection.Execute(UserRoleQuery.Update(userrole));
return userrole;
}
}
public UserRole Create(UserRole userrole)
{
if (userrole.Id == Guid.Empty)
userrole.Id = Guid.NewGuid();
using (var connection = context.CreateConnection())
{
connection.Execute(UserRoleQuery.Insert(userrole));
return userrole;
}
}
}
}
|
a2094a1ca78a005ce3922dd58e7492ae2a5ae645
|
C#
|
shendongnian/download4
|
/first_version_download2/121584-8558442-19234913-2.cs
| 3.171875
| 3
|
public DataTable getSections() {
String url = "http://<site_url>/sections.xml/sections.xml";
DataTable t = new DataTable();
t.Columns.Add("id", typeof(String));
t.Columns.Add("name", typeof(String));
HttpHandler handle = new HttpHandler();
StreamReader sr = handle.executeGET(url);
String xml = "";
List<String> id = new List<string>();
List<String> name = new List<string>();
while (sr.Peek() >= 0)
{
xml += sr.ReadLine();
}
XmlDataDocument doc = new XmlDataDocument();
doc.LoadXml(xml);
XmlReader xmlReader = new XmlNodeReader(doc);
while (xmlReader.Read()){
if (xmlReader.IsStartElement()) {
String b = xmlReader.Name;
switch (xmlReader.Name) {
case "sections":
break;
case "section":
break;
case "id":
if (xmlReader.Read())
{
id.Add(xmlReader.Value.Trim());
}
break;
case "name":
if (xmlReader.Read())
{
name.Add(xmlReader.Value.Trim());
}
break;
}
}
}
int counter = 0;
foreach (String i in id) {
DataRow r = t.NewRow();
r["id"] = i;
r["name"] = name[counter];
t.Rows.Add(r);
counter += 1;
}
return t;
}
|
da424a4e924562c117fce6ec1bbe5fcf2018b9a9
|
C#
|
ilaydaakbulut/CSharpLearningProjects
|
/MyDicrionary/Program.cs
| 3.078125
| 3
|
using System;
namespace MyDicrionary
{
class Program
{
static void Main(string[] args)
{
MyDictionary<int, string> myDictionary = new MyDictionary<int, string>();
myDictionary.Add(1, "AA");
myDictionary.Add(2, "BB");
myDictionary.Add(3, "CC");
myDictionary.Add(4, "DD");
myDictionary.Add(5, "EE");
myDictionary.Add(6, "FF");
myDictionary.Show();
}
}
}
|
a82e2600c955fa674fc37cd96e1f85bb68e8be0e
|
C#
|
alvarofachinetto/br.com.livraiashalom
|
/br.com.livrariashalom/BLL/FornecedorBLL.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using br.com.livrariashalom.DAO;
using br.com.livrariashalom.Model;
namespace br.com.livrariashalom.BLL
{
public class FornecedorBLL
{
private FornecedorDAO fornecedorDAO = new FornecedorDAO();
//metodo para receber informações do usuario e mandar para o dal
public void SalvarFornecedor(Fornecedor fornecedor)
{
try
{
fornecedorDAO.SalvarFornecedor(fornecedor);
}
catch(Exception error)
{
MessageBox.Show("erro: " + error);
}
}
public DataTable ListarFornecedor()
{
try
{
DataTable dt = new DataTable();
dt = fornecedorDAO.ListarFornecedor();
return dt;
}
catch(Exception error)
{
throw error;
}
}
public void EditarFornecedor(Fornecedor fornecedor)
{
try
{
fornecedorDAO.EditarFornecedor(fornecedor);
}catch(Exception error)
{
MessageBox.Show("Erro: " + error);
}
}
public void DeletarFornecedor(Fornecedor fornecedor)
{
try
{
fornecedorDAO.DeletarFornecedor(fornecedor);
}
catch(Exception erro)
{
MessageBox.Show("Error " + erro);
}
}
}
}
|
6e870c4aa5b3e4855681dc930498d7d9e380a517
|
C#
|
timawesomeness/SpectrumNameColorizer
|
/NamePlugin/NamePlugin.cs
| 2.734375
| 3
|
using Spectrum.API;
using Spectrum.API.Configuration;
using Spectrum.API.Interfaces.Plugins;
using Spectrum.API.Interfaces.Systems;
namespace NamePlugin {
public class Entry : IPlugin {
public string FriendlyName => "Name Colorizer";
public string Author => "timawesomeness";
public string Contact => "Steam/Discord: timawesomeness";
public APILevel CompatibleAPILevel => APILevel.UltraViolet;
private string username;
private Settings settings = new Settings(typeof(Entry));
private ClientLogic cl;
private Random random = new Random();
public void Initialize(IManager manager) {
// Generate settings if they do not exist
if (!settings.ContainsKey("Randomize Color")) {
Console.WriteLine("Name Colorizer configuration not found. Generating new configuration.");
settings.Add("Randomize Color", false);
settings.Add("Use Single Color", false);
settings.Add("Single Color Hue", 180);
settings.Add("Single Color Saturation", 100);
settings.Add("Single Color Value", 100);
settings.Add("Gradient Hue Start", 0);
settings.Add("Gradient Hue End", 360);
settings.Add("Gradient Saturation", 100);
settings.Add("Gradient Value", 100);
settings.Save();
}
// Get game's ClientLogic and the player's username.
cl = G.Sys.PlayerManager_.GetComponent<ClientLogic>();
username = G.Sys.GameManager_.GetOnlineProfileName(0);
// Update the name to be colored when the chat window is open, not colored otherwise.
Events.ChatWindow.ChatVisibilityChanged.Subscribe(data => {
if (!data.isShowing_) {
SetName(username);
} else {
UpdateName();
}
});
// Reload the colors from file
Spectrum.API.Game.Network.Chat.MessageSent += (sender, args) => {
if (args.Author == username && args.Message.Contains("!updatename"))
settings = new Settings(typeof(Entry));
};
}
/// <summary>
/// Update the player's name to be colored.
/// </summary>
private void UpdateName() {
if (settings.GetItem<bool>("Randomize Color")) {
if (settings.GetItem<bool>("Use Single Color")) {
SetName(ColorizeFlat(username, (float)random.NextDouble(), Math.Max((float)random.NextDouble(), .33f), 1f));
} else {
SetName(ColorizeGradient(username, (float)random.NextDouble(), (float)random.NextDouble(), Math.Max((float)random.NextDouble(), .33f), 1f));
}
} else {
if (settings.GetItem<bool>("Use Single Color")) {
SetName(ColorizeFlat(username,
ConvertHueToSingle(settings.GetItem<int>("Single Color Hue")),
ConvertPercentToSingle(settings.GetItem<int>("Single Color Saturation")),
ConvertPercentToSingle(settings.GetItem<int>("Single Color Value"))));
} else {
SetName(ColorizeGradient(username,
ConvertHueToSingle(settings.GetItem<int>("Gradient Hue Start")),
ConvertHueToSingle(settings.GetItem<int>("Gradient Hue End")),
ConvertPercentToSingle(settings.GetItem<int>("Gradient Saturation")),
ConvertPercentToSingle(settings.GetItem<int>("Gradient Value"))));
}
}
}
/// <summary>
/// Converts a hue wheel value (0-360) to a float (0-1) because that's what ColorEx uses.
/// </summary>
/// <param name="hue">Hue to convert</param>
/// <returns>Float from 0 to 1 that represents the hue.</returns>
private float ConvertHueToSingle(int hue) {
return Convert.ToSingle(hue / 360f);
}
/// <summary>
/// Converts a percent (0-100) to a float from 0-1 because that's what ColorEx uses.
/// </summary>
/// <param name="percent">Percent to convert</param>
/// <returns>Float from 0 to 1 that represents the hue.</returns>
private float ConvertPercentToSingle(int percent) {
return Convert.ToSingle(percent / 100f);
}
/// <summary>
/// Sets the player's name to a string
/// </summary>
/// <param name="name">String to set name to</param>
private void SetName(string name) {
cl.GetLocalPlayerInfo().GetType().GetField("username_", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(cl.GetLocalPlayerInfo(), name);
}
/// <summary>
/// Colorize a string based on a gradient on the hue wheel.
/// </summary>
/// <param name="str">String to colorize</param>
/// <param name="hueStart">Hue to start at</param>
/// <param name="hueEnd">Hue to end at</param>
/// <param name="sat">Saturation of the color</param>
/// <param name="val">Value of the color</param>
/// <returns>Colorized string</returns>
private string ColorizeGradient(string str, float hueStart, float hueEnd, float sat, float val) {
string newStr = "";
for (int i = 0; i < str.Length; i++) {
newStr += "[" + ColorEx.ColorToHexNGUI(new ColorHSB(((hueEnd - hueStart) / str.Length) * i + hueStart, sat, val, 1f).ToColor()) + "]" + str[i] + "[-]";
}
return newStr;
}
/// <summary>
/// Colorize a string based on a single color on the hue wheel.
/// </summary>
/// <param name="str">String to colorize</param>
/// <param name="hue">Hue of the color</param>
/// <param name="sat">Saturation of the color</param>
/// <param name="val">Value of the color</param>
/// <returns>Colorized string</returns>
private string ColorizeFlat(string str, float hue, float sat, float val) {
return "[" + ColorEx.ColorToHexNGUI(new ColorHSB(hue, sat, val, 1f).ToColor()) + "]" + str + "[-]";
}
public void Shutdown() {
}
}
}
|
7c3931f7e6737292b43aadf2b0a1039264fec706
|
C#
|
dadjh85/Demo4-Curso-.NetCore3.1
|
/src/Demo4/Demo4/Controllers/UserController.cs
| 2.53125
| 3
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Service.DtoModels;
using Service.UserService;
using System;
using System.Threading.Tasks;
namespace Demo4.Controllers
{
/// <summary>
/// Controler of User
/// </summary>
[Authorize(Policy = "AdminAndUser")]
public class UserController : GenericController
{
private readonly IUserService _userService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="userService"></param>
public UserController(IUserService userService)
{
_userService = userService ?? throw new ArgumentNullException(nameof(userService));
}
/// <summary>
/// GetList of User
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> GetList()
{
var result = await _userService.GetList(User.IsInRole("user"));
return Ok(result);
}
/// <summary>
/// Get a user by Id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public IActionResult Get(int id)
{
return Content($"user {id}");
}
/// <summary>
/// Add new User
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
[Authorize(Roles = "administrator")]
[HttpPost]
public IActionResult Post(DtoUserAdd item)
{
return CreatedAtAction(nameof(Get), item);
}
/// <summary>
/// Get a roles of a user
/// </summary>
/// <param name="idUser"></param>
/// <returns></returns>
[HttpGet("{idUser}/Roles")]
public IActionResult GetRoles(int idUser)
{
return Ok();
}
/// <summary>
/// Add rol to a user
/// </summary>
/// <param name="idUser"></param>
/// <param name="item"></param>
/// <returns></returns>
[HttpPost("{idUser}/Roles")]
public IActionResult AddRol(int idUser, DtoRolAdd item)
{
return CreatedAtAction(nameof(GetRoles), item);
}
}
}
|
2fffcaa36b6baf0d74496df459d461a95489aa3b
|
C#
|
radol91/BitMapEditorSolution
|
/BitMapEditor/MyBitmap.cs
| 3.046875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace BitMapEditor
{
class MyBitmap
{
private Bitmap preBitmap;
private Bitmap curBitmap;
private MyBitmapInfo bitmapInfo;
private byte[] byteArray;
//Czysta tablica pikseli bez dodatkowych bajtow - rozmiar wiersza (Width * 3 (24 bit));
private byte[,] pixelArray;
public MyBitmap(Image image, String path)
{
this.preBitmap = convertTo24bpp(image);
this.curBitmap = convertTo24bpp(image);
this.byteArray = toByteArray(curBitmap, ImageFormat.Bmp);
this.bitmapInfo = new MyBitmapInfo(image,byteArray[10],byteArray[28],path);
this.pixelArray = convertArray(this.byteArray, image.Width, image.Height);
//bitmap.Dispose();
}
// Konwertuje bitmape na 24bitowa;
public static Bitmap convertTo24bpp(Image img)
{
Bitmap bmp = new Bitmap(img.Width, img.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
Graphics gr = Graphics.FromImage(bmp);
//gr.DrawImage(bmp, new Rectangle(0, 0, img.Width, img.Height));
gr.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height));
return bmp;
}
// Przepisanie tablicy pikseli na ktorej operuje funkcja asemblerowa i przerobienie jej na bitmape.
public void finalizeAssemblerFunc()
{
this.preBitmap = this.curBitmap;
Bitmap bmp = createBitmapFromPixelArray(this.pixelArray, this.bitmapInfo.SizeX, this.bitmapInfo.SizeY);
this.curBitmap = convertTo24bpp(bmp);
}
public void finalizeAssemblerFuncSharp(byte[,] resultArray)
{
this.preBitmap = curBitmap;
this.pixelArray = (byte[,])resultArray.Clone();
Bitmap bmp = createBitmapFromPixelArray(this.pixelArray, this.bitmapInfo.SizeX, this.bitmapInfo.SizeY);
this.curBitmap = convertTo24bpp(bmp);
}
// Funkcja przerabia obrazek na tablice bajtow;
public byte[] toByteArray(Image image, ImageFormat format)
{
if (image != null)
{
MemoryStream ms = new MemoryStream();
image.Save(ms, format);
return ms.ToArray();
}
return null;
}
// Konwertuje tablice 1D na 2D;
public byte[,] convertArray(byte[] Input, int sizeX, int sizeY)
{
int width = ((Input.Length - 54) / sizeY);
int additional = width - (sizeX * 3);
int line = 0;
byte[,] Output = new byte[sizeY, width - additional];
//System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\OutFile.txt");
for (int i = 54; i < Input.Length; i += width)
{
for (int j = 0; j < width - additional; j++)
{
Output[line, j] = Input[i + j];
//sw.Write(Input[i + j] + " ");
}
//sw.WriteLine("");
line++;
}
//sw.Close();
return Output;
}
// Funkcja tworzy bitmape z tablicy bajtow;
public Bitmap createBitmapFromByteArray(byte[] pixelArray)
{
return new Bitmap(Bitmap.FromStream(new MemoryStream(pixelArray)));
}
// Funkcja tworzy bitmape z tablicy pikseli;
public Bitmap createBitmapFromPixelArray(byte[,] Input, int sizeX, int sizeY)
{
int width = ((byteArray.Length - 54) / sizeY);
int additional = width - (sizeX * 3);
byte[] additionalArray = new byte[additional];
byte[] tmpByteArray = new byte[byteArray.Length];
Bitmap bitmap = new Bitmap(sizeX, sizeY);
Array.Copy(byteArray, tmpByteArray, bitmapInfo.Offset);
int i = bitmapInfo.Offset;
for (int k = 0; k < sizeY; k++)
{
for (int n = 0; n < sizeX * 3; n++)
{
tmpByteArray[i] = Input[k, n];
i++;
}
additionalArray.CopyTo(tmpByteArray, i);
i += additional;
}
byteArray = (byte[])tmpByteArray.Clone();
return createBitmapFromByteArray(byteArray);
}
// Nadpisanie byteArray i pixelArray;
internal void updateArrays()
{
this.byteArray = this.toByteArray(this.curBitmap, ImageFormat.Bmp);
this.pixelArray = this.convertArray(this.byteArray, this.bitmapInfo.SizeX, this.bitmapInfo.SizeY);
}
public Bitmap PreviousBitmap{
get
{
return preBitmap;
}
set
{
preBitmap = value;
}
}
public Bitmap CurrentBitmap
{
get
{
return curBitmap;
}
set
{
curBitmap = value;
}
}
public MyBitmapInfo BitmapInfo
{
get
{
return bitmapInfo;
}
set
{
bitmapInfo = value;
}
}
public byte[,] PixelArray
{
get
{
return pixelArray;
}
set
{
pixelArray = value;
}
}
public byte[] ByteArray
{
get
{
return byteArray;
}
set
{
byteArray = value;
}
}
}
}
|
239ae86a66072b12cbe3e14b7d2a6c8b732118aa
|
C#
|
nesherben/SpaceInvaders
|
/Space Invaders/Assets/Scripts/Pathfinding/Pathfinder.cs
| 2.875
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Pathfinder : MonoBehaviour
{
static List<Waypoint> waypoints = new List<Waypoint>(); //Referencia a todos los waypoints de la escena
Queue<Waypoint> queue = new Queue<Waypoint>(); //Cola de procesamiento de waypoints en orden de profundidad
bool foundEndWaypoint = false;
List<Waypoint> exploredWaypoints = new List<Waypoint>();
#region splines
int splineGrade = 3;
bool splineAproximation = false;
#endregion
void Awake()
{
loadWaypoints();
}
void loadWaypoints() //Cargamos todos los waypoints en la ArrayList
{
Waypoint[] aux = FindObjectsOfType<Waypoint>();
foreach (Waypoint waypoint in aux)
{
waypoints.Add(waypoint);
}
}
public List<Vector3> getPath(List<Waypoint> patrolPath, Vector3 position, Waypoint closestPatrolWaypoint) //Camino de patrulla
{
List<Vector3> path = new List<Vector3>();
foreach(Waypoint patrolW in patrolPath)
{
path.Add(patrolW.transform.position);
}
path.Add(patrolPath[0].transform.position);
return path;
}
public List<Vector3> getPath(Vector3 start, Vector3 end)
{
//Waypoints inicial y final aproximados según las coordenadas dadas en el mundo
Waypoint startWaypoint = getCloserWaypointToCoordinates(start, waypoints);
Waypoint endWaypoint = getCloserWaypointToCoordinates(end, waypoints);
BreadthFirstSearch(startWaypoint, endWaypoint);
List<Vector3> path = createPath(startWaypoint, endWaypoint);
return path;
}
private void BreadthFirstSearch(Waypoint startWaypoint, Waypoint endWaypoint)
{
exploredWaypoints = new List<Waypoint>();
Waypoint searchCenter; //Waypoint alrededor del cual estamos buscando "vecinos"
foundEndWaypoint = false;
queue.Enqueue(startWaypoint); //Metemos en la cola de procesamiento el Waypoint incial
while (!foundEndWaypoint && queue.Count > 0)
{
searchCenter = queue.Dequeue();
exploredWaypoints.Add(searchCenter);
if (searchCenter == endWaypoint) foundEndWaypoint = true;
ExploreNeighbours(searchCenter); //Exploramos los waypoints vecinos del waypoint searchCenter
}
}
private void ExploreNeighbours(Waypoint searchCenter)
{
if (foundEndWaypoint) return;
foreach (Waypoint waypoint in searchCenter.explorableWaypoints)
{
if ( exploredWaypoints.Contains(waypoint) || queue.Contains(waypoint)) { }
else
{
queue.Enqueue(waypoint); //Colocamos los waypoints a los que puedes ir desde el searchCenter en la cola de procesamiento
waypoint.exploredFrom = searchCenter; //Marcamos que ese nodo a sido explorado desde el searchCenter
}
}
}
//Para crear el camino comenzamos desde el último nodo, vemnos desde donde ha sido explorado
//y repetimos esta operación hasta llegar al nodo inicial (seguimos el camino inverso que seguirá el agente después)
private List<Vector3> createPath(Waypoint startWaypoint, Waypoint endWaypoint)
{
List<Vector3> path = new List<Vector3>();
path.Add(endWaypoint.transform.position);
Waypoint previousWaypoint = endWaypoint.exploredFrom;
while (previousWaypoint != startWaypoint && previousWaypoint != null)
{
path.Add(previousWaypoint.transform.position);
previousWaypoint = previousWaypoint.exploredFrom;
}
path.Add(startWaypoint.transform.position);
path.Reverse(); //le damos la vuelta al camino para que coincida con el que ha de recorrer el agente
//if(splineAproximation) path = createSplinePath(path); //Tenemos un camino lineal y queremos conseguir un camino suave usando splines
return path;
}
/*private List<Vector3> createSplinePath(List<Vector3> rawPath)
{
List<Vector3> path = new List<Vector3>();
Vector3 bSpline = new Vector3();
int curveOrder = splineGrade + 1;
float splineParameter = 0;
float splineParameterIncrement = 0.01f;
float splineEndThreshold = 1.0f;
bool splineFinished = false;
float[] nodes = new float[rawPath.Count + curveOrder + 1];
for(int i = 0; i < nodes.Length; i++) nodes[i] = (float)i / (nodes.Length - 1);
while(splineParameter <= 1.0f && !splineFinished)
{
bSpline = new Vector3();
for (int i = 0; i < rawPath.Count; i++)
{
bSpline += calculateBaseFunction(i, nodes, curveOrder, splineParameter) * rawPath[i];
}
if( (bSpline - rawPath[rawPath.Count - 1]).magnitude <= splineEndThreshold) splineFinished = true;
path.Add(bSpline);
splineParameter += splineParameterIncrement;
}
return path;
}
private float calculateBaseFunction(int nodeIndex, float[] nodes, int curveOrder, float splineParameter)
{
float N = 0.0f;
if(curveOrder == 1) //NnodeIndex, 1(splineParameter)
{
if (splineParameter >= nodes[nodeIndex] && splineParameter < nodes[nodeIndex + 1]) N = 1.0f;
else N = 0.0f;
}
else //NnodeIndex, curveOrder(splineParameter)
{
N = ( (splineParameter - nodes[nodeIndex]) / (nodes[nodeIndex + curveOrder - 1] - nodes[nodeIndex])) * calculateBaseFunction(nodeIndex, nodes, curveOrder - 1, splineParameter);
N += ((nodes[nodeIndex + curveOrder] - splineParameter) / (nodes[nodeIndex + curveOrder] - nodes[nodeIndex + 1])) * calculateBaseFunction(nodeIndex + 1, nodes, curveOrder - 1, splineParameter);
}
return N;
}*/
public Waypoint getCloserWaypointToCoordinates(Vector3 v, List<Waypoint> waypoints) //Se compara la distancia entre cada waypoint con las coordenadas dadas y nos quedamos con el más cercano
{
//Presuponemos que el primer waypoint es el más cercano
Waypoint closestWaypoint = (Waypoint)waypoints[0];
float minDistance = (closestWaypoint.transform.position - v).magnitude;
foreach (Waypoint waypoint in waypoints)
{
if ((waypoint.transform.position - v).magnitude < minDistance)
{
closestWaypoint = waypoint;
minDistance = (waypoint.transform.position - v).magnitude;
}
}
return closestWaypoint;
}
public void reset()
{
foreach (Waypoint waypoint in waypoints)
{
waypoint.exploredFrom = null;
}
}
}
|
e70918e5f13b1350e99cebee778aaef1b7fae478
|
C#
|
Junior91323/Employees
|
/Employees.DAL/Repositories/EmployeesRepository.cs
| 2.796875
| 3
|
using Employees.DAL.EF;
using Employees.DAL.Entities;
using Employees.DAL.Interfaces;
using Employees.DAL.Interfaces.Repositories;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Employees.DAL.Repositories
{
public class EmployeesRepository : IEmployeesRepository
{
private EmployeeContext db;
public EmployeesRepository(EmployeeContext context)
{
this.db = context;
}
public IEnumerable<Employee> GetAll()
{
return db.Employees;
}
public IEnumerable<Employee> GetAllWithMembers()
{
return db.Employees.Include(x=>x.Job);
}
public Employee Get(int id)
{
return db.Employees.Find(id);
}
public void Create(Employee item)
{
if (item != null)
db.Employees.Add(item);
}
public void Update(Employee item)
{
if (item != null)
db.Entry(item).State = EntityState.Modified;
}
public IEnumerable<Employee> Find(Func<Employee, Boolean> predicate)
{
if (predicate != null)
return db.Employees.Where(predicate).ToList();
return db.Employees;
}
public void Delete(int id)
{
Employee item = db.Employees.Find(id);
if (item != null)
db.Employees.Remove(item);
}
}
}
|
20dd2ee46731bb988b6d166587e84b738ae0e09a
|
C#
|
TelerikHomeworks/StanHomework
|
/2. Homework Primitive Data Types and Variables/10Employee Data/Employee.cs
| 3.65625
| 4
|
using System;
//A marketing company wants to keep record of its employees. Each record would have the following characteristics:
//First name
//Last name
//Age (0...100)
//Gender (m or f)
//Personal ID number (e.g. 8 306 112 507)
//Unique employee number (27 560 000…27 569 999)
//Declare the variables needed to keep the information for a single employee using appropriate primitive data types. Use descriptive names. Print the data at the console.
class Employee
{
static void Main()
{
String nameFirst;
String nameLast;
byte age;
char Gender;
ulong personalID;
int uniqueEmployeeNumber;
}
}
|
b6f16f5347caa605e3ca4852b6b75ecc5ba14e3b
|
C#
|
diegomalta/DataStructuresAndAlgorithms
|
/src/PhoneNumbers/Program.cs
| 3.546875
| 4
|
using System;
namespace PhoneNumbers
{
class Program
{
static void Main(string[] args)
{
/*
* for given a numbers, [3,6,9]
* return with the posibles words
* that we can create using the phone keys
* --------------------
* | 1 | 2 | 3 |
* | | abc | def |
* -------------------
* | 4 | 5 | 6 |
* | ghi | jkl | mno |
* -------------------
* | 7 | 8 | 9 |
* | pqr | suv | wxyz|
* -------------------
*/
var phoneNum = new PhoneNumbers();
Console.WriteLine(string.Join(",",phoneNum.GetCombination(new int[] { 3, 6, 4 })));
}
}
}
|
30d1c1697ff85feeae74f1877a93c43b36d2cf9f
|
C#
|
micjahn/ZXing.Net
|
/Source/lib/common/GlobalHistogramBinarizer.cs
| 2.546875
| 3
|
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace ZXing.Common
{
/// <summary> This Binarizer implementation uses the old ZXing global histogram approach. It is suitable
/// for low-end mobile devices which don't have enough CPU or memory to use a local thresholding
/// algorithm. However, because it picks a global black point, it cannot handle difficult shadows
/// and gradients.
///
/// Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.
///
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// <author>Sean Owen</author>
/// </summary>
public class GlobalHistogramBinarizer : Binarizer
{
private const int LUMINANCE_BITS = 5;
private const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
private const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
private static readonly byte[] EMPTY = new byte[0];
private byte[] luminances;
private readonly int[] buckets;
/// <summary>
/// Initializes a new instance of the <see cref="GlobalHistogramBinarizer"/> class.
/// </summary>
/// <param name="source">The source.</param>
public GlobalHistogramBinarizer(LuminanceSource source)
: base(source)
{
luminances = EMPTY;
buckets = new int[LUMINANCE_BUCKETS];
}
/// <summary>
/// Applies simple sharpening to the row data to improve performance of the 1D Readers.
/// </summary>
/// <param name="y"></param>
/// <param name="row"></param>
/// <returns></returns>
public override BitArray getBlackRow(int y, BitArray row)
{
LuminanceSource source = LuminanceSource;
int width = source.Width;
if (row == null || row.Size < width)
{
row = new BitArray(width);
}
else
{
row.clear();
}
initArrays(width);
byte[] localLuminances = source.getRow(y, luminances);
int[] localBuckets = buckets;
for (int x = 0; x < width; x++)
{
localBuckets[(localLuminances[x] & 0xff) >> LUMINANCE_SHIFT]++;
}
int blackPoint;
if (!estimateBlackPoint(localBuckets, out blackPoint))
return null;
if (width < 3)
{
// Special case for very small images
for (int x = 0; x < width; x++)
{
if ((localLuminances[x] & 0xff) < blackPoint)
{
row[x] = true;
}
}
}
else
{
int left = localLuminances[0] & 0xff;
int center = localLuminances[1] & 0xff;
for (int x = 1; x < width - 1; x++)
{
int right = localLuminances[x + 1] & 0xff;
// A simple -1 4 -1 box filter with a weight of 2.
// ((center << 2) - left - right) >> 1
if (((center * 4) - left - right) / 2 < blackPoint)
{
row[x] = true;
}
left = center;
center = right;
}
}
return row;
}
/// <summary>
/// Does not sharpen the data, as this call is intended to only be used by 2D Readers.
/// </summary>
public override BitMatrix BlackMatrix
{
get
{
LuminanceSource source = LuminanceSource;
byte[] localLuminances;
int width = source.Width;
int height = source.Height;
BitMatrix matrix = new BitMatrix(width, height);
// Quickly calculates the histogram by sampling four rows from the image. This proved to be
// more robust on the blackbox tests than sampling a diagonal as we used to do.
initArrays(width);
int[] localBuckets = buckets;
for (int y = 1; y < 5; y++)
{
int row = height * y / 5;
localLuminances = source.getRow(row, luminances);
int right = (width << 2) / 5;
for (int x = width / 5; x < right; x++)
{
int pixel = localLuminances[x] & 0xff;
localBuckets[pixel >> LUMINANCE_SHIFT]++;
}
}
int blackPoint;
if (!estimateBlackPoint(localBuckets, out blackPoint))
return new BitMatrix(1, 1);
// We delay reading the entire image luminance until the black point estimation succeeds.
// Although we end up reading four rows twice, it is consistent with our motto of
// "fail quickly" which is necessary for continuous scanning.
localLuminances = source.Matrix;
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
int pixel = localLuminances[offset + x] & 0xff;
matrix[x, y] = (pixel < blackPoint);
}
}
return matrix;
}
}
/// <summary>
/// Creates a new object with the same type as this Binarizer implementation, but with pristine
/// state. This is needed because Binarizer implementations may be stateful, e.g. keeping a cache
/// of 1 bit data. See Effective Java for why we can't use Java's clone() method.
/// </summary>
/// <param name="source">The LuminanceSource this Binarizer will operate on.</param>
/// <returns>
/// A new concrete Binarizer implementation object.
/// </returns>
public override Binarizer createBinarizer(LuminanceSource source)
{
return new GlobalHistogramBinarizer(source);
}
private void initArrays(int luminanceSize)
{
if (luminances.Length < luminanceSize)
{
luminances = new byte[luminanceSize];
}
for (int x = 0; x < LUMINANCE_BUCKETS; x++)
{
buckets[x] = 0;
}
}
private static bool estimateBlackPoint(int[] buckets, out int blackPoint)
{
blackPoint = 0;
// Find the tallest peak in the histogram.
int numBuckets = buckets.Length;
int maxBucketCount = 0;
int firstPeak = 0;
int firstPeakSize = 0;
for (int x = 0; x < numBuckets; x++)
{
if (buckets[x] > firstPeakSize)
{
firstPeak = x;
firstPeakSize = buckets[x];
}
if (buckets[x] > maxBucketCount)
{
maxBucketCount = buckets[x];
}
}
// Find the second-tallest peak which is somewhat far from the tallest peak.
int secondPeak = 0;
int secondPeakScore = 0;
for (int x = 0; x < numBuckets; x++)
{
int distanceToBiggest = x - firstPeak;
// Encourage more distant second peaks by multiplying by square of distance.
int score = buckets[x] * distanceToBiggest * distanceToBiggest;
if (score > secondPeakScore)
{
secondPeak = x;
secondPeakScore = score;
}
}
// Make sure firstPeak corresponds to the black peak.
if (firstPeak > secondPeak)
{
int temp = firstPeak;
firstPeak = secondPeak;
secondPeak = temp;
}
// If there is too little contrast in the image to pick a meaningful black point, throw rather
// than waste time trying to decode the image, and risk false positives.
// TODO: It might be worth comparing the brightest and darkest pixels seen, rather than the
// two peaks, to determine the contrast.
if (secondPeak - firstPeak <= numBuckets >> 4)
{
return false;
}
// Find a valley between them that is low and closer to the white peak.
int bestValley = secondPeak - 1;
int bestValleyScore = -1;
for (int x = secondPeak - 1; x > firstPeak; x--)
{
int fromFirst = x - firstPeak;
int score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);
if (score > bestValleyScore)
{
bestValley = x;
bestValleyScore = score;
}
}
blackPoint = bestValley << LUMINANCE_SHIFT;
return true;
}
}
}
|
e907548e0477fee1c1ef6d611bac6cbe932a4494
|
C#
|
bur-lis/VKR
|
/VKR/MatrixC.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathNet.Numerics.LinearAlgebra.Complex;
using System.Numerics;
using System.Windows.Controls;
namespace VKR
{
static class MatrixC
{
static List<string> _nameGates = new List<string> { "X", "Y", "Z", "H", "T", "I","S" };
public static void addGate(string S)
{
_nameGates.Add(S);
}
public static List<string> nameGates
{
get
{
return _nameGates;
}
set
{
_nameGates = value;
}
}
public static Dictionary<string, SparseMatrix> arrayGates = new Dictionary<string, SparseMatrix>()
{ {"I", SparseMatrix.OfArray(new Complex[,] { { 1, 0 }, { 0, 1 } }) },
{"S", SparseMatrix.OfArray(new Complex[,] { { 1, 0 }, { 0, new Complex(0, 1) } }) },
{"X", SparseMatrix.OfArray(new Complex[,] { { 0, 1 }, { 1, 0 } }) },
{"Y",SparseMatrix.OfArray(new Complex[,] { { 0, new Complex(0, -1) },{ new Complex(0, 1), 0 } }) } ,
{"Z",SparseMatrix.OfArray(new Complex[,] { { 1, 0 }, {0, -1 } }) },
{"H",SparseMatrix.OfArray(new Complex[,] { { 1 / Math.Sqrt(2), 1 / Math.Sqrt(2) }, {1 / Math.Sqrt(2), -1 / Math.Sqrt(2) } }) },
{"T",SparseMatrix.OfArray(new Complex[,] { { 1, 0 },{ 0, Math.Exp((new Complex(0, 1)).Imaginary * (Math.PI / 8)) } })} };
public static SparseMatrix NewU(int v, int numberYpr, List<string> znach)
{
SparseMatrix matrix = new SparseMatrix((int)Math.Pow(2, v), (int)Math.Pow(2, v));
string[] condition = new string[v - znach.Count + 1],
binaryNumbers = MatrixC.ArrayofBinaryNumbers(matrix.ColumnCount);
string partCondition = "", s;
for (int i = 0; i < v; i++) partCondition += "*";
StringBuilder str = new StringBuilder(partCondition);
for (int i = 1; i < znach.Count; i++)
{
if (znach[i].Substring(0, 1) == "W") s = "1"; else s = "0";
str[v - Convert.ToInt32(znach[i].Substring(1, znach[i].Length - 1)) - 1] = Convert.ToChar(s);
}
partCondition = str.ToString();
List<string> lol = new List<string> { partCondition };
List<string> lol1 = fun(lol);
for (int i = 0; i < matrix.ColumnCount; i++)
{
if (lol1.Contains(binaryNumbers[i]))
{
SparseMatrix[] mas = binaryNumbers[i].Select(x => charToMat(x)).ToArray();
Console.WriteLine(mas);
mas[ v - numberYpr - 1] = arrayGates[znach[0]] * mas[v - 1 - numberYpr];
var a = mas.Aggregate((x, y) => (SparseMatrix)x.KroneckerProduct(y)).EnumerateColumns().ElementAt(0);
matrix.SetColumn(i, a);
}
else
{
var a = binaryNumbers[i].Select(x => charToMat(x)).Aggregate((x, y) => (SparseMatrix)x.KroneckerProduct(y)).EnumerateColumns().ElementAt(0);
matrix.SetColumn(i, a);
}
}
Console.Write(matrix);
return matrix;
}
private static SparseMatrix charToMat(char x)
{
if (x == '0') return SparseMatrix.OfArray(new Complex[,] { { 1 }, { 0 } });
else return SparseMatrix.OfArray(new Complex[,] { { 0 }, { 1 } });
}
private static List<string> fun(List<string> lol)
{
if (lol.Any(sss => sss.Contains('*')))
{
var abc = new List<string>();
foreach (string s in lol)
{
var abc1 = new StringBuilder(s);
var abc2 = new StringBuilder(s);
abc1[s.IndexOf('*')] = '0';
abc2[s.IndexOf('*')] = '1';
abc.Add(abc1.ToString());
abc.Add(abc2.ToString());
}
return fun(abc);
}
else
{
return lol;
}
throw new NotImplementedException();
}
public static string[] ArrayofBinaryNumbers(int size)
{
string[] binaryNumbers = new string[size];
for (int i = 0; i < size; i++)
binaryNumbers[i] = Convert.ToString(i, 2).PadLeft((int)Math.Log(size, 2), '0');
return binaryNumbers;
}
public static SparseMatrix GetMatrix(TextBox[] b, int size)
{
SparseMatrix matrix = new SparseMatrix(size, size);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
matrix[i, j] = StrinComplex(b[i * size + j].Text);
}
}
if (((SparseMatrix)matrix.ConjugateTranspose()* matrix).Equals(SparseMatrix.CreateDiagonal(size,size,1))) return matrix;
else return new SparseMatrix(0,0);
}
public static Complex StrinComplex(string sourceStr)
{
string realStr = "",
imaginaryStr = "";
int k = 0;
double realPart,
imaginaryPart;
foreach (char c in sourceStr)
{
if (c != '(' && c != ')')
if (c == ',') k++;
else
{
if (k == 0) realStr += c;
else imaginaryStr += c;
}
}
if (realStr == "") realPart = 0; else realPart = Convert.ToDouble(realStr);
if (imaginaryStr == "") imaginaryPart = 0; else imaginaryPart = Convert.ToDouble(imaginaryStr);
return new Complex (realPart, imaginaryPart);
}
public static string MatinVn(SparseMatrix matrix)
{
int size = matrix.ColumnCount;
string result = "";
string[] binaryNumbers = ArrayofBinaryNumbers(size);
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
if (matrix[i, j] != 0) result += matrix[i, j].ToString() + "|" + binaryNumbers[i] + "><" + binaryNumbers[j] + "|" + " + ";
}
if (result == "") return "";
return result.Substring(0, result.Length - 2); ;
}
public static List<SparseMatrix> MatrixTwoLevel(SparseMatrix mat)
{
List<SparseMatrix> resultmatrix = new List<SparseMatrix>();
for(int i = 0; i < mat.ColumnCount; i++)
{
for(int j = i+1; j < mat.ColumnCount; j++)
{
SparseMatrix m = SparseMatrix.CreateDiagonal(mat.ColumnCount, mat.ColumnCount, 1);
if (mat[j, i] != 0)
{
if (j == mat.ColumnCount - 1 && i == mat.ColumnCount - 2)
{
m[i, i] = Complex.Conjugate(mat[i, i]);
m[i, j] = Complex.Conjugate(mat[j, i]);
m[j, i] = Complex.Conjugate(mat[i, j]);
m[j, j] = Complex.Conjugate(mat[j, j]);
}
else
{
double n = Math.Sqrt(Math.Pow(Complex.Abs(mat[i, i]), 2) + Math.Pow(Complex.Abs(mat[j, i]), 2));
m[i, i] = Complex.Conjugate(mat[i, i]) / n;
m[i, j] = Complex.Conjugate(mat[j, i]) / n;
m[j, i] = mat[j, i] / n;
m[j, j] = -mat[i, i] / n;
}
}
resultmatrix.Add((SparseMatrix)m.ConjugateTranspose());
mat = m * mat;
}
}
List<SparseMatrix> resultmatrix1 = resultmatrix.Where(x => !x.Equals(SparseMatrix.CreateDiagonal(mat.ColumnCount, mat.ColumnCount, 1))).ToList();
foreach (SparseMatrix c in resultmatrix1)
{
Console.Write(c);
int l = 0;
if (!MatrixC.arrayGates.ContainsValue(c))
{
for (int j = 0; l < 1; j++)
{
if (!MatrixC.arrayGates.ContainsKey("U" + j.ToString()))
{
MatrixC.arrayGates.Add("U" + j.ToString(), c);
MatrixC.nameGates.Add("U" + j.ToString());
l++;
}
}
}
}
if (resultmatrix1.Count == 0) return new List<SparseMatrix> { SparseMatrix.CreateDiagonal(mat.ColumnCount, mat.ColumnCount, 1) };
return resultmatrix1;
}
public static bool UnitMatrix(SparseMatrix mat)
{
Complex coloumn = new Complex();
Complex row = new Complex();
for (int i = 0; i< mat.ColumnCount; i++)
{
coloumn += mat[i, mat.ColumnCount - i];
row += mat[mat.ColumnCount - i, i];
}
// if ((new Complex(1, 0) - row). new Complex(0.5,0) && Math.Abs(1 - Convert.ToDouble(coloumn)) < 0.5) return true;
return false;
}
}
}
|
dd9a4dbb352aeca502954304d33e3fe220244db2
|
C#
|
stefanbursuc/Bewildered-Core
|
/Runtime/UHashSet.cs
| 2.984375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Bewildered
{
// Implementation Note:
// We do not inheirt from HashShet<T> because in the ISerializationCallbackReceiver.OnBeforeSerialize() method
// we need to iterate over the items in the HashSet but for unknown
// reasons the enumerator MoveNext() will result in a null reference exception.
// Currently my suspicion is that Unity may actually be serializing some of the fields
// in the HashSet, and that is causing the exception, however I'm not sure.
/// <summary>
/// Represents a serializable set of values.
/// </summary>
/// <typeparam name="T">The type of item in the <see cref="UHashSet{T}"/>.</typeparam>
[Serializable]
public class UHashSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T>, ISerializationCallbackReceiver
{
[Serializable]
private struct SerializableValue
{
public T value;
#if UNITY_EDITOR
public bool isDuplicate;
public int index;
#endif
public SerializableValue(T value)
{
this.value = value;
#if UNITY_EDITOR
isDuplicate = false;
index = -1;
#endif
}
}
#if UNITY_EDITOR
// Set to `true` exclusivally in the property drawer. Resets to false when the domain reloads.
[NonSerialized] private bool _saveDuplicates = false;
#endif
[NonSerialized] private readonly HashSet<T> _hashSet = new HashSet<T>();
[SerializeField] private List<SerializableValue> _serializedValues = new List<SerializableValue>();
/// <summary>
/// Gets the number of items contained in the <see cref="UHashSet{T}"/>.
/// </summary>
public int Count
{
get { return _hashSet.Count; }
}
bool ICollection<T>.IsReadOnly
{
get { return ((ICollection<T>)_hashSet).IsReadOnly; }
}
public UHashSet()
{
_hashSet = new HashSet<T>();
}
public UHashSet(IEnumerable<T> collection)
{
_hashSet = new HashSet<T>(collection);
}
public UHashSet(IEqualityComparer<T> comparer)
{
_hashSet = new HashSet<T>(comparer);
}
public UHashSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
_hashSet = new HashSet<T>(collection, comparer);
}
/// <summary>
/// Adds the specified item to the <see cref="UHashSet{T}"/>.
/// </summary>
/// <param name="item">The item to add to the <see cref="UHashSet{T}"/>.</param>
/// <returns>
/// <c>true</c> if <paramref name="item"/> is added to the <see cref="UHashSet{T}"/>;
/// otherwise <c>false</c> if <paramref name="item"/> is already present.
/// </returns>
public bool Add(T item)
{
return _hashSet.Add(item);
}
void ICollection<T>.Add(T item)
{
_hashSet.Add(item);
}
/// <summary>
/// Removes the specified item from the <see cref="UHashSet{T}"/>.
/// </summary>
/// <param name="item">The <see cref="T"/> to remove.</param>
/// <returns>
/// <c>true</c> if <paramref name="item"/> is successfully found and removed; otherwise, <c>false</c>.
/// This method returns <c>false</c> if <paramref name="item"/> is not found in the <see cref="UHashSet{T}"/>
/// </returns>
public bool Remove(T item)
{
return _hashSet.Remove(item);
}
/// <summary>
/// Removes all items from the <see cref="UHashSet{T}"/>.
/// </summary>
public void Clear()
{
_hashSet.Clear();
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> contains the specified item.
/// </summary>
/// <param name="item">The item to locate in the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <see cref="UHashSet{T}"/>; otherwise <c>false</c>.</returns>
public bool Contains(T item)
{
return _hashSet.Contains(item);
}
/// <summary>
/// Removes all items in the specified collection from the <see cref="UHashSet{T}"/>.
/// </summary>
/// <param name="other">The collection of items to remove from the <see cref="UHashSet{T}"/>.</param>
public void ExceptWith(IEnumerable<T> other)
{
_hashSet.ExceptWith(other);
}
/// <summary>
/// Modifies the <see cref="UHashSet{T}"/> to contain only itemss that are present in both the <see cref="UHashSet{T}"/> and the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
public void IntersectWith(IEnumerable<T> other)
{
_hashSet.IntersectWith(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> is a proper subset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if the <see cref="UHashSet{T}"/> is a proper subset of <paramref name="other"/>; otherwise, <c>false</c>.</returns>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
return _hashSet.IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> is a proper superset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if the <see cref="UHashSet{T}"/> is a proper superset of <paramref name="other"/>; otherwise, <c>false</c>.</returns>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
return _hashSet.IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> is a subset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if the <see cref="UHashSet{T}"/> is a subset of <paramref name="other"/>; otherwise, <c>false</c>.</returns>
public bool IsSubsetOf(IEnumerable<T> other)
{
return _hashSet.IsSubsetOf(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> is a superset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if the <see cref="UHashSet{T}"/> is a superset of <paramref name="other"/>; otherwise, <c>false</c>.</returns>
public bool IsSupersetOf(IEnumerable<T> other)
{
return _hashSet.IsSupersetOf(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> and the specified collection share common items.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns>
/// <c>true</c> if the <see cref="UHashSet{T}"/> and <paramref name="other"/> share at least one common item; otherwise, <c>false</c>.
/// </returns>
public bool Overlaps(IEnumerable<T> other)
{
return _hashSet.Overlaps(other);
}
/// <summary>
/// Determines whether the <see cref="UHashSet{T}"/> and the specified collection contain the same items.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
/// <returns><c>true</c> if the <see cref="UHashSet{T}"/> and <paramref name="other"/> contain the same items; other <c>falase</c>.</returns>
public bool SetEquals(IEnumerable<T> other)
{
return _hashSet.SetEquals(other);
}
/// <summary>
/// Modifies the <see cref="UHashSet{T}"/> to contain only items that are present either in the <see cref="UHashSet{T}"/> or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
public void SymmetricExceptWith(IEnumerable<T> other)
{
_hashSet.SymmetricExceptWith(other);
}
/// <summary>
/// Modifies the <see cref="UHashSet{T}"/> to contain all items that are present in itself, the specified collection, or both.
/// </summary>
/// <param name="other">The collection to compare to the <see cref="UHashSet{T}"/>.</param>
public void UnionWith(IEnumerable<T> other)
{
_hashSet.UnionWith(other);
}
/// <summary>
/// Copies the items of the <see cref="UHashSet{T}"/> to an array.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the items copied from the <see cref="UHashSet{T}"/>.</param>
public void CopyTo(T[] array)
{
_hashSet.CopyTo(array);
}
/// <summary>
/// Copies the items of the <see cref="UHashSet{T}"/> to an array, starting at a specified array index.
/// </summary>
/// <param name="array">The one-dimensional array that is the destination of the items copied from the <see cref="UHashSet{T}"/>.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public void CopyTo(T[] array, int arrayIndex)
{
_hashSet.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="UHashSet{T}"/>.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
return _hashSet.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="UHashSet{T}"/>.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_hashSet).GetEnumerator();
}
void ISerializationCallbackReceiver.OnBeforeSerialize()
{
#if UNITY_EDITOR
// _saveDuplicates is set to false when the domain reloads. This will cause all of the serialized pairs with duplicate keys
// to be removed, since we just call Clear() on the serialized pairs.
// It would be nice if there was a way to check when the property drawer was no longer being used, and clear the duplicates then,
// but that does not seem possible at this time.
if (_saveDuplicates)
{
// Remove all serialized pairs that do *not* collide since they will already be in the dictionary
// unless they were removed from it intentionally.
for (int i = _serializedValues.Count - 1; i >= 0; i--)
{
if (!_serializedValues[i].isDuplicate)
_serializedValues.RemoveAt(i);
}
}
else
{
_serializedValues.Clear();
}
// When serializing the values of the dictionary to the list, we need to add the items to the dictionary
// in positions reletive to the duplicate key pairs. Otherwise the items will move around in the inspector
// while you are changing their keys (for example if you change it to/from being a duplicate key.
int index = 0;
bool hasDuplicateValues = _serializedValues.Count > 0;
int nextDuplicateValueIndex = hasDuplicateValues ? _serializedValues[0].index : -1;
foreach (T value in this)
{
if (hasDuplicateValues)
{
if (index < nextDuplicateValueIndex)
{
_serializedValues.Insert(index, new SerializableValue(value) { index = index });
}
else if (index > nextDuplicateValueIndex)
{
// This will happen when there are more values after the last duplicate value.
_serializedValues.Add(new SerializableValue(value) { index = index });
}
else if (index == nextDuplicateValueIndex)
{
// We increment the index until the index is different than that of a duplicate key pair's index.
while (index == nextDuplicateValueIndex && index < _serializedValues.Count)
{
index++;
if (index < _serializedValues.Count)
nextDuplicateValueIndex = _serializedValues[index].index;
}
_serializedValues.Insert(index, new SerializableValue(value) { index = index });
}
}
else
{
_serializedValues.Add(new SerializableValue(value) { index = index });
}
index++;
}
#else
_serializedValues.Clear();
foreach (var value in this)
{
_serializedValues.Add(new SerializableValue(value));
}
#endif
}
void ISerializationCallbackReceiver.OnAfterDeserialize()
{
Clear();
#if UNITY_EDITOR
for (int i = 0; i < _serializedValues.Count; i++)
{
// We make sure that each serialized item has it's proper index value.
// For example, when reordering with a ReorderableList in the inspector, they will become out of sync.
var pair = _serializedValues[i];
pair.index = i;
_serializedValues[i] = pair;
if (!Contains(_serializedValues[i].value))
{
Add(_serializedValues[i].value);
SetValueDuplicatedState(i, false);
}
else
{
SetValueDuplicatedState(i, true);
}
}
#else
foreach (var serializedItem in _serializedItems)
{
Add(serializedItem.value);
}
#endif
}
#if UNITY_EDITOR
private void SetValueDuplicatedState(int index, bool isDuplicate)
{
var pair = _serializedValues[index];
pair.isDuplicate = isDuplicate;
_serializedValues[index] = pair;
}
#endif
}
}
|
4f6864d3c9279d6f12f2cf0cb1ac8a36a5cc6894
|
C#
|
theunrepentantgeek/vsgraph
|
/src/Niche.Graph/Edge.cs
| 3.265625
| 3
|
using System;
using System.Drawing;
using Niche.Shared;
namespace Niche.Graphs
{
/// <summary>
/// A graph edge, linking two nodes
/// </summary>
public class Edge
{
/// <summary>
/// Gets the node from which this edge starts
/// </summary>
public Node Start
{
get;
private set;
}
/// <summary>
/// Gets the node to which edge finishes
/// </summary>
public Node Finish
{
get;
private set;
}
/// <summary>
/// Gets the arrowhead to display at the finish of this edge
/// </summary>
public ArrowShape ArrowHead
{
get;
private set;
}
/// <summary>
/// Gets the arrowhead to display at the finish of this edge
/// </summary>
public ArrowShape ArrowTail
{
get;
private set;
}
/// <summary>
/// Gets the color to use for this edge
/// </summary>
public Color Color
{
get;
private set;
}
/// <summary>
/// Gets a value indicating whether this edge should be used for ranking
/// </summary>
public bool Constraining
{
get;
private set;
}
/// <summary>
/// Gets a value indicating the pen width to use for lines
/// </summary>
public double PenWidth
{
get;
private set;
}
/// <summary>
/// Initializes a new instance of the <see cref="Edge"/> class.
/// </summary>
/// <param name="start">Start node from which this edge begins</param>
/// <param name="finish">Finish node to which this edge runs</param>
public Edge(Node start, Node finish)
{
if (start == null)
{
throw new ArgumentNullException("start", "Start node is mandatory");
}
if (finish == null)
{
throw new ArgumentNullException("finish", "Finish node is mandatory");
}
Start = start;
Finish = finish;
}
/// <summary>
/// Initializes a new instance of the <see cref="Edge"/> class.
/// </summary>
/// <param name="start">Start node from which this edge begins</param>
/// <param name="finish">Finish node to which this edge runs</param>
/// <param name="style">Style to apply to the edge</param>
public Edge(Node start, Node finish, EdgeStyle style)
: this(start, finish)
{
if (style == null)
{
throw new ArgumentNullException("style", "Style is a mandatory parameter");
}
ArrowHead = style.ArrowHead;
ArrowTail = style.ArrowTail;
Color = style.Color;
Constraining = style.Constraining;
PenWidth = style.PenWidth;
}
/// <summary>
/// Visit the passed visitor and return the result generated
/// </summary>
/// <param name="visitor">The visitor itself.</param>
/// <typeparam name="TReturn">Type of return value.</typeparam>
/// <returns>Result generated by the Visitor.</returns>
public TReturn Visit<TReturn>(IGraphVisitor<TReturn> visitor)
where TReturn : class
{
Require.NotNull("visitor", visitor);
return visitor.VisitEdge(this);
}
}
}
|
9db12c5d17a766a675db08131f7a03e77419e507
|
C#
|
qLaudiu/SP_FootballManager
|
/SP_FootballManager/Staff.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SP_FootballManager
{
public class Staff : IStaff
{
private List<IStaff> children = new List<IStaff>();
public Staff() : base()
{
}
public override void Add(IStaff child)
{
if (!children.Contains(child))
{
children.Add(child);
}
}
public override bool Remove(IStaff child)
{
if (!children.Contains(child))
{
children.Remove(child);
return true;
}
else
{
return false;
}
}
protected internal override void Display(int depth)
{
base.DisplayIntern(depth);
depth++;
foreach (IStaff child in children)
{
child.Display(depth);
}
}
}
}
|
26c50b49067774aa9629f27a5b7c018aebe529b2
|
C#
|
wxm001/Wei.OA
|
/Wei.OA.Common/LogHelper.cs
| 2.75
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wei.OA.Common
{
using System.Threading;
//public delegate void WriteLogDel(string str);
public class LogHelper
{
public static Queue<string> ExceptionStringQueue=new Queue<string>();
public static List<ILogWriter> LogWriterList=new List<ILogWriter>();
//public static WriteLogDel WriteLogDelFunc;
static LogHelper()
{
//WriteLogDelFunc=new WriteLogDel(WriteLogToFile);
//WriteLogDelFunc += WriteLogToDb;
LogWriterList.Add(new TextFileWriter());
LogWriterList.Add(new SqlServerWriter());
LogWriterList.Add(new Log4NetWriter());
//从队列中获取错误消息写到日志文件中
ThreadPool.QueueUserWorkItem(
o =>
{
while (true)
{
lock (ExceptionStringQueue)
{
if (ExceptionStringQueue.Count > 0)
{
string str = ExceptionStringQueue.Dequeue();
//把异常信息写到日志文件;变化点:可能写到日志文件或者数据库或者都写。
//观察者模式
foreach (var logWriter in LogWriterList)
{
logWriter.WriteLogInfo(str);
}
}
else
{
Thread.Sleep(30);
}
}
}
});
}
//public static void WriteLogToFile(string txt)
//{
//}
//public static void WriteLogToDb(string txt)
//{
//}
/// <summary>
/// 错误消息写入队列
/// </summary>
/// <param name="exceptionText"></param>
public static void WriteLog(string exceptionText)
{
lock (ExceptionStringQueue)
{
ExceptionStringQueue.Enqueue(exceptionText);
}
}
}
}
|
3e7bcca29fb732918562278c7c3ed30647a0a674
|
C#
|
jaskarans-optimus/Induction
|
/Dot Net Induction/XML and Serialization/Assignment28/Assignment28/Program.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment28
{
class Program
{
static void Main(string[] args)
{
Student student = new Student(2, "abc", 60);
Student student1 = new Student(4, "Sarab", 70);
Student student2 = new Student(5, "bad", 80);
var students= new List<Student>();
students.Add(student);
students.Add(student1);
students.Add(student2);
List<Student> deSerializedStudents;
Console.WriteLine("---------------Binary Serialization--------------");
Console.WriteLine("Before Serialization \n");
foreach (Student student3 in students)
{
Console.WriteLine(student3);
}
Student.BinarySerialization("iCalibrator.dat", students);
deSerializedStudents = Student.BinaryDeserialization("iCalibrator.dat");
Console.WriteLine("After Serialization \n {0}");
foreach (Student student3 in deSerializedStudents)
{
Console.WriteLine(student3);
}
//Console.WriteLine("---------------XML Serialization-----------------");
//Console.WriteLine("Before Serialization \n ");
//foreach (Student student3 in students)
//{
// Console.WriteLine(student3);
//}
//Student.XmlSerialization("iCalibrator.xml", students);
//deSerializedStudents = Student.XmlDeserialization("iCalibrator.xml");
//Console.WriteLine("After Serialization:");
//foreach (Student student3 in deSerializedStudents)
//{
// Console.WriteLine(student3);
//}
Console.WriteLine("---------------Soap Serialization-----------------");
Console.WriteLine("Before Serialization \n ");
foreach (Student student3 in students)
{
Console.WriteLine(student3);
}
Student.SoapSerialization("iCalibrator.soap", students);
Student[] deSerializedStudents1 = Student.SoapDeserialization("iCalibrator.soap");
Console.WriteLine("After Serialization \n ");
foreach (Student student3 in deSerializedStudents1)
{
Console.WriteLine(student3);
}
Console.ReadKey();
}
}
}
|
7295af45aebd086727af639d128e2fa549baaf2c
|
C#
|
Volha525/ola-bardezkaja
|
/LetterAa.cs
| 3.4375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LetterAa
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите предложение");
string sentense = Console.ReadLine();
char[] charSentense = sentense.ToCharArray();
char a = 'а';
char A = 'А';
for (int i = 0; i < charSentense.Length; i++)
{
if (charSentense[i] == a)
{
charSentense[i] = A;
}
}
sentense = new string(charSentense);
Console.WriteLine($"Новое предложение: {sentense}");
Console.ReadLine();
}
}
}
|
2249dffbe5b1d61ce61522b30702edf384f9ebf2
|
C#
|
estrela530/bermuda
|
/ShipGame/Actor/Player.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ShipGame.Device;
using ShipGame.Def;
using ShipGame.Util;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
namespace ShipGame.Actor
{
class Player : GameObject
{
private Vector2 direction;
private Vector2 stickDirection;
private double stickAngle;
//private Vector2 directionV;
//private Vector2 slideModify;
//private bool isEndFlag;
private float speed = 4.0f;
//private float rotation;
private IGameObjectMediator mediator;//ゲームオブジェクト仲介者
private double angle;
private float flyingSpeed;
private Vector2 upVec = new Vector2(0.0f, -1.0f);
public Player(Vector2 position, float rotation, Vector2 origin, GameDevice gameDevice,
IGameObjectMediator mediator)
: base("red", position, rotation, origin, 32, 32, gameDevice)
{
velocity = Vector2.Zero;
isDeadFlag = false;
this.mediator = mediator;
this.origin = new Vector2(16, 16);
this.rotation = 0.0f;
angle = -Math.PI / 2;
flyingSpeed = 0;
}
public override object Clone()
{
//自分と同じ型のオブジェクトを自分の情報で生成
return new Player(this);
}
/// <summary>
/// コピーコンストラクタ
/// </summary>
/// <param name="other"></param>
public Player(Player other)
: this(other.position, other.rotation, other.origin, other.gameDevice, other.mediator)
{
}
public override void Draw(Renderer renderer)
{
renderer.DrawTexture(name, position);
}
/// <summary>
/// ヒット通知
/// </summary>
/// <param name="gameObject"></param>
public override void Hit(GameObject gameObject)
{
//当たった方向の取得
Direction dir = this.CheckDirection(gameObject);
//ゲームオブジェクトがだったら死ぬ
if (gameObject.ToString().Contains(""))
{
if (dir != Direction.Top)
{
isDeadFlag = true;
}
}
//ゲームオブジェクトがブロックのオブジェクトか?
//if (gameObject.ToString().Contains(""))
//{
// //プレイヤーとブロックの衝突面処理
// HitBlock(gameObject);
//}
}
public void PlayerMove()
{
//velocity.X = Input.GetLeftStickground(PlayerIndex.One).X* speed;
//if (Input.IsButtonPress(PlayerIndex.One,Buttons.B))
//{
// velocity.Y = velocity.Y+ 1.1f;
//}
//flyingSpeed = (float)Math.Sqrt(velocity.X * velocity.X + velocity.Y * velocity.Y); //velocityの大きさをflyingSpeedに入れる。
//velocity = Input.GetLeftStickladder(PlayerIndex.One) * speed;
//position = position - velocity;
// 角度計算
stickDirection = Input.GetLeftSticksky(PlayerIndex.One);
stickAngle = Math.Atan2(stickDirection.X, stickDirection.Y);
if (stickDirection != Vector2.Zero)
{
direction = stickDirection;
direction.Normalize();
angle = stickAngle;
Console.WriteLine("direction = " + direction);
//Console.WriteLine("angle = " + angle);
}
flyingSpeed += (float)Math.Sin(angle);
//flyingSpeed = (float)Math.Sqrt(velocity.X * velocity.X + velocity.Y * velocity.Y); //velocityの大きさをflyingSpeedに入れる。
velocity = flyingSpeed * direction;
if (stickDirection != Vector2.Zero)
{
position += (velocity / 5);
}
else
{
direction.Normalize();
}
}
public override void Update(GameTime gameTime)
{
PlayerMove();
}
}
}
|
0bcf91c41ce3bdaf0f89e6d52380cefaea243682
|
C#
|
BenjaminBruton/PartsInventoryProject
|
/C968 - BFM1 - BBruton Inventory Project/AddPart.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace C968___BFM1___BBruton_Inventory_Project
{
public partial class AddPart : Form
{
public AddPart()
{
InitializeComponent();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
lblRadio.Text = "Machine ID";
textBoxRadio.Text = "ID Ex: '1234'";
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
lblRadio.Text = "Company Name";
textBoxRadio.Text = "Ex: Acme, Inc";
}
private void btnSave_Click(object sender, EventArgs e)
{
if (Int32.Parse(textBoxMax.Text) < Int32.Parse(textBoxMin.Text))
{
MessageBox.Show("MINIMUM cannot be GREATER than the MAXIMUM.");
return;
}
if (radioButton1.Checked)
{
Classes.InHousePart inHouse = new Classes.InHousePart((Classes.Inventory.Parts.Count + 1), AddPartNameBoxText, AddPartInvBoxText, AddPartPriceBoxText, AddPartMaxBoxText, AddPartMinBoxText, int.Parse(AddPartMachComBoxText));
Classes.Inventory.AddPart(inHouse);
}
else
{
Classes.OutsourcedPart outsourced = new Classes.OutsourcedPart((Classes.Inventory.Parts.Count + 1), AddPartNameBoxText, AddPartInvBoxText, AddPartPriceBoxText, AddPartMaxBoxText, AddPartMinBoxText, AddPartMachComBoxText);
Classes.Inventory.AddPart(outsourced);
}
this.Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBoxRadio_MouseClick(object sender, MouseEventArgs e)
{
textBoxRadio.Clear();
}
//The four methods below are for form validatiion.
private void textBoxInv_Validating(object sender, CancelEventArgs e)
{
try
{
Int32.Parse(textBoxInv.Text);
}
catch (FormatException)
{
MessageBox.Show("Please enter an integer\n in the 'Inventory' field.");
}
}
private void textBoxPrice_Validating(object sender, CancelEventArgs e)
{
try
{
Decimal.Parse(textBoxPrice.Text);
}
catch (FormatException)
{
MessageBox.Show("Please enter an integer\n in the 'Price' field.");
}
}
private void textBoxMax_Validating(object sender, CancelEventArgs e)
{
try
{Int32.Parse(textBoxMax.Text);
}
catch (FormatException)
{
MessageBox.Show("Please enter an integer\n in the 'Max' field.");
}
}
private void textBoxMin_Validating(object sender, CancelEventArgs e)
{
try
{
Int32.Parse(textBoxMin.Text);
}
catch (FormatException)
{
MessageBox.Show("Please enter an integer\n in the 'Min' field.");
}
}
}
}
|
42dbe232efb3bf2da9e6eee5d6fd6b0a32cf3705
|
C#
|
k2workflow/Chasm
|
/src/SourceCode.Chasm/Blob.cs
| 2.9375
| 3
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using SourceCode.Clay.Buffers;
namespace SourceCode.Chasm
{
[DebuggerDisplay("{ToString(),nq,ac}")]
public readonly struct Blob : IEquatable<Blob>
{
private static readonly Blob s_empty;
/// <summary>
/// A singleton representing an empty <see cref="Blob"/> value.
/// </summary>
public static ref readonly Blob Empty => ref s_empty;
private readonly byte[] _data;
public IReadOnlyList<byte> Data => _data;
public Blob(byte[] data)
{
_data = data;
}
public override string ToString()
=> nameof(_data.Length) + ": " + (_data == null ? "null" : $"{_data.Length}");
public bool Equals(Blob other)
=> BufferComparer.Array.Equals(_data, other._data);
public override bool Equals(object obj)
=> obj is Blob other
&& Equals(other);
public override int GetHashCode()
=> BufferComparer.Memory.GetHashCode(_data);
public static bool operator ==(Blob x, Blob y) => x.Equals(y);
public static bool operator !=(Blob x, Blob y) => !(x == y);
}
}
|
18ed933521c26cae464b65541cef43bd6bc8732b
|
C#
|
ChristianArnold/OVT_Hololens
|
/Assets/Scripts/Functionality Scripts/vectorsScripts/EVectorScript.cs
| 2.515625
| 3
|
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
/// E Vector Script
/// Author: Thomas Fitzgerald
/// Draws a line from the origin to the perigee of the current orbit
/// So easy a caveman could do it
public class EVectorScript : MonoBehaviour{
public Library lib;
public InputField rF, pF;
private Vector3 origin, perigee;
private LineRenderer line;
private float baseOrthoSize, orthoSize;
void Start(){
origin = new Vector3(0, 0, 0);
line = GetComponent<LineRenderer>();
line.SetPosition(0, origin);
line.SetWidth(3, 3);
line.SetVertexCount(2);
baseOrthoSize = Camera.main.orthographicSize;
}
void OnEnable(){
if (lib.checkA() && lib.checkE() && lib.checkI() && (lib.checkR()||rF.text=="undef") && (lib.checkP()||pF.text=="undef")){
perigee = OrbitScript.CalculateState(lib.getA()*290f, lib.getE(), lib.getI(),lib.getR(), lib.getP(), 0);
}
line = GetComponent<LineRenderer>();
line.SetPosition(1, perigee);
}
void Update(){
if (lib.checkA() && lib.checkE() && lib.checkI() && (lib.checkR()||rF.text=="undef") && (lib.checkP()||pF.text=="undef")){
perigee = OrbitScript.CalculateState(lib.getA()*290f, lib.getE(), lib.getI(),lib.getR(), lib.getP(), 0);
}
line.SetPosition(1, perigee);
orthoSize = Camera.main.orthographicSize;
//set width based on camera size
if ((orthoSize - baseOrthoSize) < 0) line.SetWidth(3, 3);
else line.SetWidth(3 + (orthoSize - baseOrthoSize) * 0.01f, 3 + (orthoSize - baseOrthoSize) * 0.01f);
}
}
|
4a2a4c4d7bab4ae68d95ca726d1ba78ac7239075
|
C#
|
brungardtdb/Craps
|
/Craps/Program.cs
| 3.65625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Craps
{
// create random-number generator for use in method RollDice
private static Random randomNumbers = new Random();
// enumeration with constants that represent the game status
private enum Status { Continue, Won, Lost}
// enumeration with constants that repressent the common rolls of the dice
private enum DiceNames
{
SnakeEyes = 2,
Trey = 3,
Seven = 7,
YoLeven = 11,
BoxCars = 12,
}
// plays one game of craps
static void Main()
{
int balance = 1000;
do
{
Console.WriteLine($"Please enter your wager: (balance is {balance})");
int wager = Convert.ToInt32(Console.ReadLine());
Console.WriteLine($"Your wager is {wager} dollars.");
if (wager <= balance)
{
// gameStatus can ontain Continue, Won, or Lost
Status gameStatus = Status.Continue;
int myPoint = 0; // point of no win or loss on first roll
int sumOfDice = RollDice(); // first roll of dice
// determine game status and point based on first roll
switch ((DiceNames)sumOfDice)
{
case DiceNames.Seven: // win with 7 on the first roll
case DiceNames.YoLeven: // win with 11 on the first roll
gameStatus = Status.Won;
break;
case DiceNames.SnakeEyes: // lose with 2 on the first roll
case DiceNames.Trey: // lose with 3 on the first roll
case DiceNames.BoxCars: // lose with 12 on the first roll
gameStatus = Status.Lost;
break;
}
// while game is not complete
while (gameStatus == Status.Continue) // game not won or lost
{
sumOfDice = RollDice(); // roll dice again
// determine game status
if (sumOfDice == myPoint) // win by making point
{
gameStatus = Status.Won;
}
else
{
//lose by rolling 7 before point
if (sumOfDice == (int)DiceNames.Seven)
{
gameStatus = Status.Lost;
}
}
}
// display won or lost message
if (gameStatus == Status.Won)
{
Console.WriteLine("Player Wins");
balance = balance + wager;
Console.WriteLine($"Your new balance is: {balance}\n");
}
else
{
Console.WriteLine("Player Loses\n");
balance = balance - wager;
Console.WriteLine($"Your new balance is: {balance}\n");
}
}
else
{
Console.WriteLine($"Wager exceeded balance, please enter a new wager\n");
}
} while (balance > 0);
}
// roll dice, calculate sum and display results
static int RollDice()
{
// pick random die values
int die1 = randomNumbers.Next(1, 7); // first die roll
int die2 = randomNumbers.Next(1, 7); // second die roll
int sum = die1 + die2; // sum of all die values
// display results of this roll
Console.WriteLine($"Player rolled {die1} + {die2} = {sum}");
return sum; // return sum of the dice
}
}
|
803f8d25ec3e4be60c8398e87a0d331579db55d9
|
C#
|
brauniks/FileWorker
|
/FileWorker/Tools/XmlTransformer.cs
| 2.578125
| 3
|
namespace FileWorker.Tools
{
using Interfaces;
using PdfFile.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Xsl;
/// <summary>
/// Defines the <see cref="XmlTransformer" />
/// </summary>
public class XmlTransformer : IProcessBarHandler, IXmlTools
{
public XmlTransformer()
{
this.cachedTransforms = new Dictionary<string, XslCompiledTransform>();
this.args = new FileEventArgs();
}
/// <summary>
/// Gets or sets the eventHandler
/// </summary>
public Action<FileEventArgs> eventHandler { get; set; }
/// <summary>
/// Gets or sets the args
/// </summary>
public FileEventArgs args { get; set; }
/// <summary>
/// Defines the cachedTransforms
/// </summary>
public Dictionary<string, XslCompiledTransform> cachedTransforms { get; set; }
/// <summary>
/// The TransormXMl
/// </summary>
/// <param name="inputXml">The <see cref="string[]"/></param>
/// <param name="inputXslt">The <see cref="string"/></param>
/// <param name="outputPathDirectory">The <see cref="string"/></param>
/// <returns>The <see cref="Task"/></returns>
public async Task TransformXML(string[] inputXml, string inputXslt, string outputPathDirectory)
{
await Task.Factory.StartNew(() =>
{
var xsltString = File.ReadAllText(inputXslt, Encoding.UTF8);
XslCompiledTransform transform = this.GetAndCacheTransform(xsltString);
this.args.totalFiles = inputXml.Length;
Parallel.For(0, inputXml.Length, (i) =>
{
var fileName = Path.GetFileName(inputXml[i]);
this.args.currentFileName = fileName;
var xmlString = File.ReadAllText(inputXml[i], Encoding.UTF8);
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
transform.Transform(reader, null, results);
}
File.WriteAllText($"{outputPathDirectory}\\{fileName.Replace(".xml", ".html")}", results.ToString());
this.args.currentFile++;
this.eventHandler?.Invoke(this.args);
});
});
}
/// <summary>
/// The GetAndCacheTransform
/// </summary>
/// <param name="xslt">The <see cref="string"/></param>
/// <returns>The <see cref="XslCompiledTransform"/></returns>
public XslCompiledTransform GetAndCacheTransform(string xslt)
{
XslCompiledTransform transform;
if (!cachedTransforms.TryGetValue(xslt, out transform))
{
transform = new XslCompiledTransform();
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
transform.Load(reader);
}
cachedTransforms.Add(xslt, transform);
}
return transform;
}
}
}
|
3308c622fe61585448bdf84fe41e45d584da3817
|
C#
|
phbraganca/Insurance
|
/Insurance.Domain/RepositoryBase.cs
| 3.078125
| 3
|
using Insurance.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Insurance.Domain
{
public class RepositoryBase<T>: IRepositoryBase<T> where T : class
{
private DataContext<T> Context { get; set; }
public RepositoryBase(DataContext<T> context)
{
this.Context = context ?? throw new ArgumentNullException(nameof(context));
}
public void Save(T obj)
{
this.Context.Set(obj);
}
public void Delete(T obj)
{
this.Context.Remove(obj);
}
public IList<T> GetAll(T obj)
{
return this.Context.List(obj);
}
public T Get(T obj)
{
return this.Context.FirstOrDefault(obj);
}
public void Update(T obj)
{
this.Context.Update(obj);
}
}
}
|
dd3a1b0d785035b1f68dce77ee24f45bf95fc76e
|
C#
|
manikantatps/The-complete-aspnet-mvc-5-course
|
/Vidly/Controllers/MoviesController.cs
| 3.015625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;
using Vidly.ViewModels;
namespace Vidly.Controllers
{
public class MoviesController : Controller
{
// GET: Movies/Random
public ActionResult Random()
{
var movie = new Movie() { Name = "Shrek!" };
//return View(movie);
//Content Will just return the text
//return Content("Hello World!!!!");
//HttpNotFound will return 404 not found page
//return HttpNotFound();
//EmptyResult return nothing
//return new EmptyResult();
//RedirectToAction navigates the controller action as specified Parameters are action, controller and parameters(parameters will be shown in URL)
//return RedirectToAction("Contact", "Home", new { page = 1, sortBy = "name" });
//View Data
//View data is a old approach and "Movie" is changed it will thoughts a null error. Instead of this passing model is the best way.
//ViewData["Movie"] = movie;
//return View();
//ViewModel Example
var customers = new List<Customer>
{
new Customer{Id=1, Name="Customer 1" },
new Customer{Id=2, Name="Customer 2" },
new Customer{Id=3, Name="Customer 3" }
};
var viewModel = new RandomMovieViewModel
{
Movie = movie,
Customers = customers
};
return View(viewModel);
}
// GET: Movies/Edit/{id}
public ActionResult Edit(int id)
{
return Content("Id=" + id);
}
//This is for optional parameters
// GET: Movies
//public ActionResult Index(int? pageIndex, string sortBy)
//{
// if (!pageIndex.HasValue)
// pageIndex = 1;
// if (String.IsNullOrWhiteSpace(sortBy))
// sortBy = "name";
// return Content(String.Format("pageIndex={0}&sortBy={1}", pageIndex, sortBy));
//}
//Example for custom route and the custom route is added in "RouteConfig.cs"
// GET: Movies/Released
//Below Route is without constraints
//[Route("movies/released/{year}/{month}")]
//Below Route is with constraints below regular expression will accepts only 2 digit number for month
//[Route("movies/released/{year}/{month:regex(\\d{2})}")]
//Below Route is with multiple constraints below regular expression will accepts only 2 digit number for month and range will be 1 to 12
[Route("movies/released/{year}/{month:regex(\\d{2}):range(1,12)}")]
public ActionResult ByReleaseDate(int year, int month)
{
return Content(year + "/" + month);
}
//For S2 Excersice
public ActionResult Index()
{
var movies = new List<Movie>
{
new Movie{Name="Shrek!"},
new Movie{Name="Dragon"}
};
var viewModel = new RandomMovieViewModel
{
Movies = movies
};
return View(viewModel);
}
}
}
|
ebd6629133d26b0c9caa800457c0941a22187a8c
|
C#
|
zubenkoivan/algorithms
|
/Algorithms/Graphs/StronglyConnectedComponents.cs
| 3.203125
| 3
|
using System.Collections.Generic;
namespace Algorithms.Graphs
{
public class StronglyConnectedComponents
{
private readonly DirectedGraph graph;
private readonly VerticeColors colors;
private DirectedGraph invertedGraph;
private int verticeIndex;
private readonly int[] verticesInFinishTimeOrder;
private List<List<int>> components;
public StronglyConnectedComponents(DirectedGraph graph)
{
this.graph = graph;
colors = new VerticeColors(graph.VerticesCount);
verticesInFinishTimeOrder = new int[graph.VerticesCount];
verticeIndex = graph.VerticesCount;
}
public int[][] Find()
{
ForwardDFS();
BackwardDFS();
var result = new int[components.Count][];
for (int i = 0; i < result.Length; ++i)
{
result[i] = components[i].ToArray();
}
return result;
}
private void ForwardDFS()
{
for (int i = 0; i < graph.VerticesCount; ++i)
{
if (colors[i] == VerticeColor.White)
{
ForwardDFS(i);
}
}
}
private void ForwardDFS(int vertice)
{
colors[vertice] = VerticeColor.Black;
foreach (int edgeEnd in graph.OutgoingEdgeEnds(vertice))
{
if (colors[edgeEnd] == VerticeColor.White)
{
ForwardDFS(edgeEnd);
}
}
--verticeIndex;
verticesInFinishTimeOrder[verticeIndex] = vertice;
}
private void BackwardDFS()
{
colors.Reset();
invertedGraph = graph.Invert();
components = new List<List<int>>();
for (int i = 0; i < verticesInFinishTimeOrder.Length; ++i)
{
if (colors[i] == VerticeColor.White)
{
var component = new List<int>();
components.Add(component);
BackwardDFS(i, component);
}
}
}
private void BackwardDFS(int vertice, List<int> component)
{
colors[vertice] = VerticeColor.Black;
component.Add(vertice);
foreach (int edgeEnd in invertedGraph.OutgoingEdgeEnds(vertice))
{
if (colors[edgeEnd] == VerticeColor.White)
{
BackwardDFS(edgeEnd, component);
}
}
}
}
}
|
7fbb0439c3500b9a8e91e89f4a45c1d7d65678a9
|
C#
|
gergelyposa/MetalGearLiquid_WPF
|
/MetalGearLiquid_WPF/MetalGearLiquid/WpfApp1/Persistance/MetalGearLiquidFileDataAccess.cs
| 2.75
| 3
|
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace MetalGearLiquid.Persistence
{
public class MetalGearLiquidFileDataAccess : MetalGearLiquidDataAccess
{
/// <summary>
/// Fájl betöltése.
/// </summary>
/// <param name="path">Elérési útvonal.</param>
/// <returns>A fájlból beolvasott játéktábla.</returns>
///
public async Task<MetalGearLiquidTable> LoadAsync(String path)
{
try
{
using StreamReader reader = new StreamReader(path);
String line = await reader.ReadLineAsync();
String[] numbers = line.Split(' ');
Int32 tableSizeX = Int32.Parse(numbers[0]);
Int32 tableSizeY = Int32.Parse(numbers[1]);
Pair tableSize = new Pair(tableSizeX, tableSizeY);
MetalGearLiquidTable table = new MetalGearLiquidTable(tableSize);
Int32 time = Int32.Parse(numbers[2]);
table._elapsedTime = time;
table.maxGuards = Int32.Parse(numbers[3]);
int numberOfGuards = 0;
table.Guards = new Guard[table.maxGuards];
table.spotPoints = new Pair[table.maxGuards * 24];
for (Int32 i = 0; i < table.TableSize.x; i++)
{
line = await reader.ReadLineAsync();
numbers = line.Split(' ');
for (Int32 j = 0; j < table.TableSize.y; j++)
{
table.SetValue(i, j, table.GetFieldTypeFromNumeric(Int32.Parse(numbers[j])));
if(table[i,j] == FieldType.Player)
{
table.Snek = new Pair(i, j);
}
if(table[i,j] == FieldType.Guard)
{
table.Guards[numberOfGuards] = new Guard(new Pair(i, j), 'w');
numberOfGuards++;
}
}
}
return table;
}
catch
{
throw new MetalGearLiquidDataException();
}
}
}
}
|
a885e78f5319a9ad42bab948d78ae4bc78ce08fe
|
C#
|
WanftMoon/codesignal
|
/CodeSignal/Arcade/Intro/ExploringTheWaters.cs
| 3.796875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace CodeSignal.Arcade.Intro
{
public class ExploringTheWaters
{
/// <remarks>
/// Several people are standing in a row and need to be divided into two teams. The first person goes into team 1, the second goes into team 2, the third goes into team 1 again, the fourth into team 2, and so on.
///
/// You are given an array of positive integers - the weights of the people.Return an array of two integers, where the first element is the total weight of team 1, and the second element is the total weight of team 2 after the division is complete.
///
/// Example
///
/// For a = [50, 60, 60, 45, 70], the output should be
///alternatingSums(a) = [180, 105].
///
///Input/Output
///
///[execution time limit] 3 seconds(cs)
///
///[input]
/// array.integer a
///
/// Guaranteed constraints:
/// 1 ≤ a.length ≤ 105,
/// 45 ≤ a[i] ≤ 100.
///
/// [output] array.integer
/// </remarks>
public static int[] AlternatingSums(int[] a)
{
int[] sum = new int[2] { 0, 0 };
for (int i = 0; i < a.Length; i++)
{
sum[i % 2] += a[i];
}
return (sum);
}
/// <remarks>
/// Given a rectangular matrix of characters, add a border of asterisks(*) to it.
///
/// Example
///
/// For
///
/// picture = ["abc",
/// "ded"]
/// the output should be
///
/// addBorder(picture) = ["*****",
/// "*abc*",
/// "*ded*",
/// "*****"]
/// Input/Output
///
/// [execution time limit] 3 seconds(cs)
///
/// [input] array.string picture
///
/// A non-empty array of non-empty equal-length strings.
///
/// Guaranteed constraints:
/// 1 ≤ picture.length ≤ 100,
/// 1 ≤ picture[i].length ≤ 100.
///
/// [output] array.string
///
/// The same matrix of characters, framed with a border of asterisks of width 1.
/// </remarks>
public static string[] AddBorder(string[] picture)
{
List<string> lst = new List<string>();
int size = picture[0].Length;
//top frame
lst.Add(new string('*', size + 2));
for (int i = 0; i < picture.Length; i++)
{
//add begin frame
lst.Add($"*{picture[i]}*");
}
//bottom frame
lst.Add(new string('*', size + 2));
return (lst.ToArray());
}
/// <remarks>
/// Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
/// Given two arrays a and b, check whether they are similar.
///
/// Example
///
///
/// For a = [1, 2, 3] and b = [1, 2, 3], the output should be
/// areSimilar(a, b) = true.
///
///
/// The arrays are equal, no need to swap any elements.
///
///
/// For a = [1, 2, 3] and b = [2, 1, 3], the output should be
/// areSimilar(a, b) = true.
///
///
/// We can obtain b from a by swapping 2 and 1 in b.
///
/// For a = [1, 2, 2] and b = [2, 1, 1], the output should be
/// areSimilar(a, b) = false.
///
///
/// Any swap of any two elements either in a or in b won't make a and b equal.
///
///
/// Input/Output
///
/// [execution time limit] 3 seconds (cs)
///
/// [input] array.integer a
///
///
/// Array of integers.
///
/// Guaranteed constraints:
/// 3 ≤ a.length ≤ 105,
/// 1 ≤ a[i] ≤ 1000.
///
///
/// [input] array.integer b
///
///
/// Array of integers of the same length as a.
///
/// Guaranteed constraints:
/// b.length = a.length,
/// 1 ≤ b[i] ≤ 1000.
///
///
/// [output] boolean
///
/// true if a and b are similar, false otherwise.
///
/// ranked solution:
/// var diffs = A.Select((_, i) => i).Where(_ => A[_] != B[_]).ToArray();
/// return diffs.Length == 0 || diffs.Length == 2 && A[diffs[0]] == B[diffs[1]] && B[diffs[0]] == A[diffs[1]];
/// </remarks>
public static bool AreSimilar(int[] a, int[] b)
{
List<int> diff = new List<int>();
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
diff.Add(i);
}
if (diff.Count() == 0) return (true);
if (diff.Count() != 2) return (false);
int id1 = diff[0];
int id2 = diff[1];
if (a[id1] == b[id2] && a[id2] == b[id1]) return true;
return (false);
}
/// <remarks>
/// You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.
///
/// Example
///
/// For inputArray = [1, 1, 1], the output should be
/// arrayChange(inputArray) = 3.
///
/// Input/Output
///
/// [execution time limit] 3 seconds(cs)
///
/// [input]
/// array.integer inputArray
///
/// Guaranteed constraints:
/// 3 ≤ inputArray.length ≤ 105,
/// -105 ≤ inputArray[i] ≤ 105.
///
/// [output]
/// integer
///
/// The minimal number of moves needed to obtain a strictly increasing sequence from inputArray.
/// It's guaranteed that for the given test cases the answer always fits signed 32-bit integer type.
/// </remarks>
public static int ArrayChange(int[] inputArray)
{
int moves = 0;
int diff = 0;
for (int i = 1; i < inputArray.Length; i++)
{
if (inputArray[i] <= inputArray[i - 1])
{
diff = inputArray[i - 1] - inputArray[i] + 1;
inputArray[i] += diff;
moves += diff;
}
}
return (moves);
}
/// <remarks>
/// Given a string, find out if its characters can be rearranged to form a palindrome.
///
/// Example
///
/// For inputString = "aabb", the output should be
/// palindromeRearranging(inputString) = true.
///
/// We can rearrange "aabb" to make "abba", which is a palindrome.
///
/// Input/Output
///
/// [execution time limit] 3 seconds (cs)
///
/// [input] string inputString
///
/// A string consisting of lowercase English letters.
///
/// Guaranteed constraints:
/// 1 ≤ inputString.length ≤ 50.
///
/// [output] boolean
///
/// true if the characters of the inputString can be rearranged to form a palindrome, false otherwise.
///
/// return input.GroupBy(c => c)
/// .Where(g => g.Count() % 2 == 1)
/// .Count() <= 1;
/// </remarks>
public static bool PalindromeRearranging(string inputString)
{
List<char> lst = new List<char>();
for (int i = 0; i < inputString.Length; i++)
{
if (lst.Contains(inputString[i]))
lst.Remove(inputString[i]);
else
lst.Add(inputString[i]);
}
if (inputString.Length % 2 == 0 && lst.Count == 0 ||
inputString.Length % 2 == 1 && lst.Count == 1)
return (true);
else
return (false);
}
}
}
|
0d04fa8f3346ba6712d44ec774208b916c4c8ae6
|
C#
|
austinhill42/CSharp
|
/Programming Assignment 2/Programming Assignment 2/Car.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace Programming_Assignment_2
{
public class Car
{
// Using default get/set since data is validated by the form before continuing
public double CostOfOwnership { get; set; }
public double CostOfGas { get; set; }
public double CityMileage { get; set; }
public double HwyMileage { get; set; }
public double Price { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public static int NumCars { get; set; }
public static double CityMilesDriven { get; set; }
public static double HwyMilesDriven { get; set; }
public static List<Car> Cars { get; set; }
public static List<double> PricePerGal { get; set; }
// fully parameterized constructor, all parameters optional
public Car(string make = "", string model = "", double price = 0, double cityMileage = 0,
double hwyMileage = 0)
{
Make = make;
Model = model;
Price = price;
CityMileage = cityMileage;
HwyMileage = hwyMileage;
CostOfGas = (from ppg in PricePerGal
select ((CityMilesDriven / CityMileage) + (HwyMilesDriven / HwyMileage)) * ppg).Sum();
CostOfOwnership = this.Price + this.CostOfGas;
} // Car
// calculate cost of gas
public void CalculateCostOfGas()
{
// calculates the cost of gas if the values weren't set during constructor call
CostOfGas = (from ppg in PricePerGal
select ((CityMilesDriven / CityMileage) + (HwyMilesDriven / HwyMileage)) * ppg).Sum(); ;
} // CalculateCostOfGas
// calculate cost of ownership
public void CalculateCostOfOwnership()
{
// calculates the cost of ownership if the values weren't set during constructor call
CostOfOwnership = this.Price + this.CostOfGas;
} // CalculateCostOfOwnership
// overrided ToString
public override string ToString()
{
return string.Format("{0,-15} {1,-20} MPG rating: city: {2,-4} highway: {3, -4}" +
"\r\n{4,-37}Initial cost: {5, -8:C2} \r\n{6,-37}Ten year cost of gas: {7,-5:C2}" +
"\r\n{8,-37}Ten year cost of ownership: {9,-6:C2}\r\n", this.Make, this.Model,
this.CityMileage, this.HwyMileage, " ", this.Price, " ", this.CostOfGas, " ",
this.CostOfOwnership);
} // ToString
// format output into neat rows/comlums
public static string FormattedOutput()
{
string output = "";
int year = DateTime.Today.Year;
// order cars by cost of ownership
List<Car> orderedCars = (from Car cars in Car.Cars
orderby cars.CostOfOwnership ascending
select cars).ToList();
/** print the header **/
output += string.Format("{0,-15}", "Year:");
// getting the next 10 consecutive years
for (int i = 0; i < 10; i++)
output += string.Format("{0,-8}", year++.ToString());
output += string.Format("\r\n{0,-15}", "Price per Gal:");
foreach (double i in Car.PricePerGal)
output += string.Format("{0, -8}", i);
output += string.Format("\r\n\r\nMiles driven: {0,-8} {1,-9}", "city:", "highway:");
output += string.Format("\r\n{0,-13} {1,-8:##,###} {2,-9:##,###}", " ",
Car.CityMilesDriven, Car.HwyMilesDriven);
output += string.Format("\r\n\r\n");
/** print each cars data **/
foreach (Car car in orderedCars)
output += car.ToString() + "\r\n";
return output;
} // FormattedOutput
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main_Form());
} // Main
} // class Car
} // namespace Programming_Assignment_2
|
711514294acae4ee404fddc9e0d2e85a7c1354f4
|
C#
|
ReissZachary/TinkerJems
|
/TinkerJems.Wpf/MainWindow.xaml.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace TinkerJems.Wpf
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void AddNewJewelryItem_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string command;
//checks to see command OR checks to see if user control
if(btn.Tag != null)
{
command = btn.Tag.ToString();
if (command.Contains("."))
{
}
else
{
ProcessButtonsCommand(command);
}
}
}
private void EditJewelryItem_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string command;
//checks to see command OR checks to see if user control
if (btn.Tag != null)
{
command = btn.Tag.ToString();
if (command.Contains("."))
{
}
else
{
ProcessButtonsCommand(command);
}
}
}
public void ProcessButtonsCommand(string command)
{
switch (command.ToLower())
{
case "exit":
this.Close();
break;
default:
break;
}
}
}
}
|
d00743a37edb86f02f23f6c74d2474d2dab7f71e
|
C#
|
martincostello/lambda-test-server
|
/tests/AwsLambdaTestServer.Tests/ReverseFunctionTests.cs
| 2.546875
| 3
|
// Copyright (c) Martin Costello, 2019. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using System.Text.Json;
using MartinCostello.Testing.AwsLambdaTestServer;
namespace MyFunctions;
public static class ReverseFunctionTests
{
[Fact]
public static async Task Function_Reverses_Numbers()
{
// Arrange
using var server = new LambdaTestServer();
using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await server.StartAsync(cancellationTokenSource.Token);
int[] value = new[] { 1, 2, 3 };
byte[] json = JsonSerializer.SerializeToUtf8Bytes(value);
LambdaTestContext context = await server.EnqueueAsync(json);
using var httpClient = server.CreateClient();
// Act
await ReverseFunction.RunAsync(httpClient, cancellationTokenSource.Token);
// Assert
Assert.True(context.Response.TryRead(out LambdaTestResponse? response));
Assert.True(response!.IsSuccessful);
Assert.NotNull(response.Content);
var actual = JsonSerializer.Deserialize<int[]>(response.Content);
Assert.NotNull(actual);
Assert.Equal(new[] { 3, 2, 1 }, actual);
}
}
|
54fd3195ef51903d5ed50b1ed8728af1da69df16
|
C#
|
IvanovVadym/RemoteEducation
|
/RemoteEducationApi/Application/Students/Commands/CreateStudent/CreateStudentCommandValidator.cs
| 2.671875
| 3
|
using FluentValidation;
namespace Application.Students.Commands.CreateStudent
{
public class CreateStudentCommandValidator : AbstractValidator<CreateStudentCommand>
{
public CreateStudentCommandValidator()
{
RuleFor(v => v.FirstName)
.NotEmpty().WithMessage("FirstName is required.")
.MaximumLength(20).WithMessage("FirstName must not exceed 20 characters.");
RuleFor(v => v.LastName)
.NotEmpty().WithMessage("LastName is required.")
.MaximumLength(20).WithMessage("LastName must not exceed 20 characters.");
}
}
}
|
b915e4608b8ae1ee1887cd600de12ae018e75842
|
C#
|
Knagis/CommonMarkSharp
|
/CommonMarkSharp/BlockParsers/IBlockParserExtensions.cs
| 2.953125
| 3
|
namespace CommonMarkSharp.BlockParsers
{
public static class IBlockParserExtensions
{
public static int ParseMany<T>(this IBlockParser<T> parser, ParserContext context, string input)
where T : class
{
return parser.ParseMany(context, new Subject(input));
}
public static int ParseMany<T>(this IBlockParser<T> parser, ParserContext context, Subject subject)
where T : class
{
var count = 0;
while (!subject.EndOfString)
{
if (!parser.Parse(context, subject))
{
return count;
}
count += 1;
}
return count;
}
}
}
|
450a038a95e32765e12eacdee09d8630a7c4794a
|
C#
|
matei-tm-csv/ApiVersioningDemo
|
/DemoVersioning/Controllers/v2_0/WeatherForecastController.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using ApiVersioningDemo.Configuration;
using ApiVersioningDemo.Models.v2_0;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace ApiVersioningDemo.Controllers.v2_0
{
/// <summary>
/// WeatherForecast class
/// </summary>
[ApiController]
[ApiV2_0]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class WeatherForecastController : BaseWeatherForecastController
{
/// <summary>
/// WeatherForecast constructor
/// </summary>
/// <param name="logger">logger</param>
public WeatherForecastController(ILogger<WeatherForecastController> logger) : base(logger)
{
}
/// <summary>
/// Get the weather forecast (Expand to see remarks)
/// </summary>
/// <remarks>The method does not need to be explicitly decorated with <b>[MapToApiVersion("2.0")]</b>.<br /> It inherits the attribute from the class level</remarks>
/// <param name="version">The version parameter</param>
/// <returns>A collection of WeatherForecast</returns>
[HttpGet]
public IEnumerable<WeatherForecast> Get(ApiVersion version)
{
Log(version);
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)],
ExtraInfo = "some extra info " + Summaries[rng.Next(Summaries.Length)].Length
})
.ToArray();
}
}
}
|