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
|
|---|---|---|---|---|---|---|
b9b3017af89b5680c0abc37c24db93ed03b5693c
|
C#
|
radhakrishnan-sphata/FlightBoard
|
/ClassLibrary1/Security/BasicSecurity.cs
| 2.828125
| 3
|
using FlightBoard.Core.Services;
using System;
using System.Security.Cryptography;
using System.Text;
namespace FlightBoard.Core.Security
{
public class BasicSecurity
{
public static string key = "fb$123";
public static string Encrypt(string data)
{
try
{
TripleDESCryptoServiceProvider cryptoServiceProvider = new TripleDESCryptoServiceProvider();
byte[] hash = new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(BasicSecurity.key));
cryptoServiceProvider.Key = hash;
cryptoServiceProvider.Mode = CipherMode.ECB;
byte[] bytes = Encoding.ASCII.GetBytes(data);
return Convert.ToBase64String(cryptoServiceProvider.CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length));
}
catch (Exception ex)
{
LoggerService.logger.Error(ex);
throw ex;
}
}
public static string Decrypt(string data)
{
try
{
TripleDESCryptoServiceProvider cryptoServiceProvider = new TripleDESCryptoServiceProvider();
byte[] hash = new MD5CryptoServiceProvider().ComputeHash(Encoding.ASCII.GetBytes(BasicSecurity.key));
cryptoServiceProvider.Key = hash;
cryptoServiceProvider.Mode = CipherMode.ECB;
byte[] inputBuffer = Convert.FromBase64String(data);
return Encoding.ASCII.GetString(cryptoServiceProvider.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length));
}
catch (Exception ex)
{
LoggerService.logger.Error(ex);
throw ex;
}
}
public static string GeneratePassword()
{
try
{
string str1 = "abcdefghijklmnopqrstuvwxyz0123456789#+@&$ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string str2 = "";
Random random = new Random();
for (int index = 0; index <= 7; ++index)
{
int startIndex = random.Next(0, str1.Length - 1);
str2 += str1.Substring(startIndex, 1);
}
return str2;
}
catch (Exception ex)
{
LoggerService.logger.Error(ex);
throw ex;
}
}
}
}
|
ddae950bc69c6ca9e59b157c957c9f8fb56254fd
|
C#
|
akilhoffer/Reactor
|
/Reactor/Configuration/IConfigurationStore.cs
| 2.96875
| 3
|
namespace Reactor.Configuration
{
public interface IConfigurationStore
{
/// <summary>
/// Stores the configuration value at the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
void StoreConfigurationValue(string key, string value);
/// <summary>
/// Gets the configuration value at the specified key.
/// <remarks>This method first searches all cached configuration elements. If none match the key
/// specified, a search in application configuration will be performed.</remarks>
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The string representation of the value found at the specified key.</returns>
string GetConfigurationValue(string key);
/// <summary>
/// Clears this instance.
/// </summary>
void Clear();
}
}
|
8b161879ceeffbf9430d4fed2a40f9579ebb20ac
|
C#
|
jahin44/ASP_DOT_NET
|
/Console/CSharp-Features/Threads/Program.cs
| 3.53125
| 4
|
using System;
using System.Threading;
namespace Threads
{
class Program
{
static void Main(string[] args)
{
var program = new Program();
var Thread1 = new Thread(program.PrintNumbers1);
var Thread2 = new Thread(new ThreadStart(PrintNumbers2));
Thread1.Start();
Thread2.Start();
}
void PrintNumbers1()
{
for(var i = 0; i < 100; i ++)
{
Console.WriteLine($"Number 1:{i}");
Thread.Sleep(0);
}
}
static void PrintNumbers2()
{
for (var i = 0; i < 100; i ++)
{
Console.WriteLine($"Number 2:{i}");
Thread.Sleep(0);
}
}
}
}
|
c158a337a36120f46214c35fbb0b6cc603dedd78
|
C#
|
Bushische/LeetCodeTests
|
/Medium/Problem_0062.cs
| 3.4375
| 3
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Collections.Specialized;
namespace LeetCodeTests
{
public abstract class Problem_0062
{
/*
A robot is located at the top-left corner of a m x n grid(marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.The robot is trying to reach the bottom-right corner of the grid(marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 3 x 7 grid.How many possible unique paths are there?
Note: m and n will be at most 100.
*/
public static void Test()
{
Solution sol = new Solution();
/*
var input = new int[] { 2, 7, 11, 15 };
Console.WriteLine($"Input array: {string.Join(", ", input)}");
*/
int m = 3;
int n = 7;
Console.WriteLine($"For m={m} and n={n} -> {sol.UniquePaths(m, n)} unique paths (wait 28)");
m = 1;
n = 7;
Console.WriteLine($"For m={m} and n={n} -> {sol.UniquePaths(m, n)} unique paths (wait 1)");
m = 7;
n = 1;
Console.WriteLine($"For m={m} and n={n} -> {sol.UniquePaths(m, n)} unique paths (wait 1)");
m = 7;
n = 2;
Console.WriteLine($"For m={m} and n={n} -> {sol.UniquePaths(m, n)} unique paths (wait 7)");
m = 2;
n = 100;
Console.WriteLine($"For m={m} and n={n} -> {sol.UniquePaths(m, n)} unique paths (wait 7)");
}
public class Solution
{
public int UniquePaths_find(int m, int n)
{
// all cells at first row can be achieved only by ONE path
// all cells at first column also can be achieved only by ONE path
// all other cells can be achieved by SUM paths of cell from left and from top
int[] row = new int[n];
for (int ind = 0; ind < n; ind++)
row[ind] = 1;
for (int rind = 1; rind < m; rind++)
{
for (int col = 1; col < n; col++)
row[col] += row[col - 1];
}
return row[n - 1];
}
// Through Permutation formula
public int UniquePaths(int m, int n)
{
if ((m == 1) || (n == 1))
return 1;
// need make m-1 + n-1 steps
// just calculat Permutations by formula
m = m - 1;
n = n - 1;
// need m < n
if (m > n)
{
int tmp = m;
m = n;
n = tmp;
}
// calculate (m+n)! / (m!*n!)
long result = 1;
int j = 1;
long resj = 1;
for (int i = m + 1; i <= m + n; i++, j++)
{
result *= i;
result /= j;
resj *= j;
}
//result = result / resj;
return (int) result;
}
}
}//public abstract class Problem_
}
|
20016b65008cc1aec8422fbfb8bf446689bfa5b3
|
C#
|
horseyhorsey/RetroDb
|
/src/Data/RetroDb.DataSqlite/Context/RetroDbContext.cs
| 2.609375
| 3
|
using Microsoft.EntityFrameworkCore;
using RetroDb.Data;
using System;
using System.IO;
namespace RetroDb.DataSqlite
{
public class RetroDbContext : DbContext
{
public DbSet<Developer> Developers { get; set; }
public DbSet<Emulator> Emulators { get; set; }
public DbSet<Game> Games { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<GameSystem> GamingSystems { get; set; }
public DbSet<HiScore> HiScores { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
public DbSet<Publisher> Publishers { get; set; }
public DbSet<Tool> Tools { get; set; }
private string _conString = string.Empty;
public RetroDbContext(): this (@"Data Source=C:\ProgramData\RetroDb\RetroDb.Db")
{
}
public RetroDbContext(string connectionstring)
{
if (string.IsNullOrWhiteSpace(_conString))
_conString = connectionstring;
if (!File.Exists(connectionstring.Replace("Data Source=", string.Empty)))
this.Database.Migrate();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite(_conString);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Emulator>(e =>
{
e.HasIndex(f => new { f.Name , f.Version, f.Executable}).IsUnique();
});
modelBuilder.Entity<Developer>(e =>
{
e.HasIndex(f => new { f.Name }).IsUnique();
});
modelBuilder.Entity<Publisher>(e =>
{
e.HasIndex(f => new { f.Name }).IsUnique();
});
modelBuilder.Entity<Genre>(e =>
{
e.HasIndex(f => f.Name).IsUnique();
});
//assign unique id for name of system
modelBuilder.Entity<GameSystem>(e =>
{
e.HasIndex(f => f.Name).IsUnique();
});
modelBuilder.Entity<Game>(g =>
{
g.HasIndex(f => new { f.Title, f.FileName, f.Description, f.SystemId, f.ManufacturerId, f.GenreId, f.Year})
.IsUnique();
});
modelBuilder.Entity<Manufacturer>(e =>
{
e.HasIndex(f => f.Name).IsUnique();
});
modelBuilder.Entity<Tool>(e =>
{
e.HasIndex(f => new { f.Name}).IsUnique();
});
}
}
}
|
b5582c46b572d6c80b1437c64415aaca1dfa2d19
|
C#
|
thaotrant/SeleniumWebdriver
|
/ComponentHelper/ButtonHelper.cs
| 2.71875
| 3
|
using OpenQA.Selenium;
namespace SeleniumWebdriver.ComponentHelper
{
public class ButtonHelper
{
private static IWebElement element;
public static bool IsButtonEnabled(By locator)
{
element = GenericHelpers.GetElement(locator);
return element.Enabled;
}
public static void ClickOnButton(By locator)
{
element = GenericHelpers.GetElement(locator);
element.Click();
}
public static string GetButtonText(By locator)
{
element = GenericHelpers.GetElement(locator);
if (element.GetAttribute("value") == null)
return string.Empty;
else
return element.GetAttribute("value");
}
}
}
|
671bd9ab8e60ae6cf6849c1b4c58c6f171e0a89b
|
C#
|
PavelArbuzovKgd/2Lesson
|
/2Lesson/Task3.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _2Lesson
{
class Task3
{
int c = 0;
public int CalcRec(int a, int b)
{
for (int i = 0; i < 2; i++)
{
int n = a;
if (i == 0)
{
n++;
}
else
{
n *= 2;
}
if (n < b) CalcRec(n, b);
else
if (n == b) c++;
}
return c;
}
}
}
|
4aedfe0e04f63ff9c89d2494d5a95e4d2b129713
|
C#
|
InaGlushkova/CookBook
|
/CookBook/ViewModel/RegisterViewModel.cs
| 2.734375
| 3
|
using CookBook.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
namespace CookBook.ViewModel
{
class RegisterViewModel : ViewModelBase
{
public RecipeStoreDBEntities _ctx = new RecipeStoreDBEntities();
private List<User> usersList;
public RelayCommand RegisterCommand{ set; get; }
public RelayCommand BackCommand { set; get; }
private string Password { set; get; }
private string RePassword { set; get; }
public RegisterViewModel()
{
Background = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\LoginScreen.png", UriKind.Absolute));
RegisterCommand = new RelayCommand(Register, RegistrationIsValid);
BackCommand = new RelayCommand(Back);
usersList = _ctx.Users.ToList();
}
private BitmapImage _background;
public BitmapImage Background
{
get
{
return _background;
}
set
{
if (_background != value)
_background = value;
RaisePropertyChanged("Background");
}
}
private void Back(object obj)
{
var login = new MainWindow();
login.Show();
CloseWindow();
}
private string _RegStatus;
public string RegStatus
{
get
{
return _RegStatus;
}
set
{
if (_RegStatus != value)
{
_RegStatus = value;
RaisePropertyChanged("RegStatus");
}
}
}
private bool RegistrationIsValid(object obj)
{
var value = (object[])obj;
TextBox username = (TextBox)value[0];
PasswordBox boxPass = (PasswordBox)value[1];
PasswordBox reBoxPass = (PasswordBox)value[2];
Password = boxPass.Password;
RePassword = reBoxPass.Password;
if (username.Text.ToString().Length != 0)
{
if ((Password.CompareTo(RePassword) == 0) && (Password.Length >= 6))
{
RegStatus = " ";
return true;
}
else
{
if(RePassword.Length >= Password.Length && RePassword.Length >= 6)
{
RegStatus = "Passwords don't match.";
}
else if (Password.Length <= 6 && Password.Length != 0 && RePassword.Length != 0)
{
RegStatus = "Password too short.";
}
return false;
}
}
else
{
return false;
}
}
private void Register(object obj)
{
if (obj == null) return;
var value = (object[])obj;
TextBox username = (TextBox)value[0];
PasswordBox boxPass = (PasswordBox)value[1];
PasswordBox boxRePass = (PasswordBox)value[2];
User user = usersList.Find(x => x.UserName.ToString() == username.Text.ToString());
if (user == null)
{
user = new User();
Password = boxPass.Password;
user.Passw = Password;
user.UserName = username.Text.ToString();
_ctx.Users.Add(user);
_ctx.SaveChangesAsync();
var Main = new MainWindow();
Main.Show();
CloseWindow();
}
else
{
MessageBox.Show("Username already taken.");
username.Clear();
boxPass.Clear();
boxRePass.Clear();
}
}
}
}
|
dfd9b512830cd0415ca202701ff291a68ece278b
|
C#
|
martinkrivanek/Cajovna
|
/branches/src/Cajovna/Cajovna/Models/PolozkaMenu.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Cajovna.Models
{
public class PolozkaMenu
{
public int polozkaMenuID { get; set; }
public double price_sell { get; set; }
[Required]
public DateTime date_added { get; set; }
[Required]
public bool avalible { get; set; }
[Required]
public String name { get; set; }
public String description { get; set; }
public virtual List<Slozeni> recipe { get; set; }
// CONSTRUCTORs
public PolozkaMenu()
{
//recipe = new List<Slozeni>();
avalible = false;
date_added = DateTime.Now;
}
// METHODs
/* calculates and returns the total buying price of the materials */
public double price_buy()
{
double total = 0;
foreach (Slozeni item in recipe)
{
total += item.price();
}
return total;
}
/* creates and returns the string of the specific accesibility */
public String getAccesibility()
{
// in the future, there will be check if the materials are in stock
return (avalible) ? "v prodeji" : "neprodává se";
}
}
}
|
ab231c1244e0993ff6c6846d17fc601879e4bec9
|
C#
|
shendongnian/download4
|
/first_version_download2/127810-9080512-20564444-2.cs
| 3.109375
| 3
|
public static class DatabaseManager
{
//set connection string for SQL Server Express Edition
static string connString = @"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=DocumentStore;Integrated Security=True;Pooling=False";
//method to save document to database
public static bool SaveDocumentToDatabase(MemoryStream msDocument, DocumentType docType, string documentName)
{
//keep track of the save status
bool isSaved = false;
//create database connection
SqlConnection sqlConnection = new SqlConnection(connString);
try
{
sqlConnection.Open();
}
catch (Exception ex)
{
Settings.LogException(ex);
Console.WriteLine("Unable to open database connection");
isSaved = false;
}
string commandText = "INSERT INTO Documents (DocumentType, DocumentName, DocumentContent, CreateDate) VALUES('" + docType + "','" + documentName + "', @DocumentContent ,'" + DateTime.Now + "')";
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
sqlCommand.Parameters.AddWithValue("DocumentContent", msDocument.ToArray());
try
{
sqlCommand.ExecuteNonQuery();
Console.WriteLine("Document saved successfully");
isSaved = true;
}
catch(Exception ex)
{
Console.WriteLine("Unable to save the document to database");
Settings.LogException(ex);
isSaved = false;
}
//close database connect
sqlConnection.Close();
return isSaved;
}
public static bool LoadDocumentFromDataBase(DocumentType docType)
{
//keep track of the retrieve status
bool isRetrieved = false;
//create database connection
SqlConnection sqlConnection = new SqlConnection(connString);
try
{
sqlConnection.Open();
}
catch(Exception ex)
{
Console.WriteLine("Unable to open database connection");
Settings.LogException(ex);
isRetrieved = false;
}
string commandText = "SELECT * FROM Documents WHERE DocumentType ='" + docType + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(commandText, sqlConnection);
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
DataTable dtDocuments = new DataTable();
try
{
sqlDataAdapter.Fill(dtDocuments);
Console.WriteLine("Document retrieved successfully");
isRetrieved = true;
}
catch(Exception ex)
{
Console.WriteLine("Unable to retrieve documents from database");
Settings.LogException(ex);
isRetrieved = false;
}
}
}
|
0ed85c9aa95eb6db27f5ed92e66cf036c3ed8947
|
C#
|
squidblinkgames/reverie-server
|
/Reverie/Cache/WorldCache.cs
| 2.765625
| 3
|
namespace Reverie.Cache
{
using System;
using System.Collections.Generic;
using PrimitiveEngine;
public static class WorldCache
{
private readonly static Dictionary<EntityWorld, ReverieState> cache;
#region Constructors
static WorldCache()
{
cache = new Dictionary<EntityWorld, ReverieState>();
}
#endregion
public static ReverieState CreateCache(EntityWorld world)
{
if (cache.ContainsKey(world))
throw new ArgumentException("New world key already exists in WorldCache.");
ReverieState newState = new ReverieState();
cache.Add(world, newState);
return newState;
}
public static ReverieState GetCache(EntityWorld world)
{
if (!cache.ContainsKey(world))
throw new ArgumentException("World key not found in WorldCache.");
return cache[world];
}
// TODO: Method to flush cache to database.
// TODO: Method to read cache from database.
}
}
|
57d918cb65a7e19716cdc42fec69cebf67d725d3
|
C#
|
Mohammad-Ali-romani/convid-19
|
/WebApplication1/DBHnadler.cs
| 2.953125
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
namespace WebApplication1
{
public class DBHnadler
{
employee emp;
public DBHnadler()
{
}
public DBHnadler(employee emp)
{
this.emp = emp;
}
public DataSet GetAllItems()
{
string sql = "select * from tblStudents";
return ProjectDB.ExcuteDataSet(sql);
}
public employee GetItemsByID()
{
string sql = "select * from tblStudents where ID=" + emp.empId;
DataTable tb = ProjectDB.ExcuteDataTable(sql);
emp.Name = tb.Rows[0][1].ToString();
emp.Gender = tb.Rows[0][2].ToString();
emp.Marks = (int)tb.Rows[0][3];
return emp;
}
public int UpdateItemByID(int id)
{
string sql = string.Format("update tblStudents set Name='{0}', Gender='{1}', TotalMarks={2} where ID={3}",
emp.Name,
emp.Gender,
emp.Marks,
id);
return ProjectDB.ExcuteNonQuery(sql);
}
public int DelelteItemByID()
{
string sql = string.Format("delete from tblStudents where ID={0}",
emp.empId);
return ProjectDB.ExcuteNonQuery(sql);
}
public int AddNewItem()
{
string sql = string.Format("insert into tblStudents (Name,Gender,TotalMarks) values ('{0}',{1},{2})",
emp.Name,
emp.Gender,
emp.Marks);
return ProjectDB.ExcuteNonQuery(sql);
}
public object CountItems()
{
string sql = string.Format("select count(*) from tblStudents");
return ProjectDB.ExcuteScalar(sql);
}
}
}
|
c5ea21b49e8845d141e64ba6e56417af83bb56db
|
C#
|
banksemi/Gachon-Village
|
/GachonServer/MainServer/Network/NetworkMessageList.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NetworkLibrary;
using Newtonsoft.Json.Linq;
namespace MainServer
{
/// <summary>
/// 이 클래스는 소켓에 메세지를 캡슐화를 한것처럼 쉽게 전송할 수 있도록 지원합니다.
/// </summary>
static class NetworkMessageList
{
/// <summary>
/// 소켓에 Tip 메세지 (안드로이드일 경우 토스트 메세지)를 전송합니다.
/// </summary>
/// <param name="socket"></param>
/// <param name="message"></param>
public static void TipMessage(ESocket socket, string message)
{
JObject json = new JObject();
json["type"] = NetworkProtocol.TipMessage;
json["message"] = message;
socket.Send(json);
}
public static void SendMessageResult(ESocket socket, bool result)
{
JObject json = new JObject();
json["type"] = NetworkProtocol.SendPost;
json["result"] = result;
socket.Send(json);
}
/// <summary>
/// 유저에게 새로운 홈워크 정보를 알립니다.
/// </summary>
public static void AddHomework(ESocket socket, string course_name, string title, DateTime end)
{
JObject item = new JObject();
item["type"] = NetworkProtocol.Homework_Add;
item["title"] = "[" + course_name + "] " + title;
item["date"] = end;
socket.Send(item);
}
}
}
|
2ca42b87e63cf92db90d6a6925e1a812535f6079
|
C#
|
AleOshiro/taller-vi
|
/TrabajosPracticos/TrabajosPracticos/Circulo.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TrabajosPracticos
{
class Circulo : Interface
{
private double radio, area, perimetro, pi = Math.PI;
public Circulo(double radio)
{
this.radio = radio;
}
public double CalcularArea()
{
area = pi * Math.Pow(radio,2);
return area;
}
public double CalcularPerimetro()
{
perimetro = 2 * pi * radio;
return perimetro;
}
}
}
|
3e06e238052ad75ee57c881d5cad9b158f8677b2
|
C#
|
MuhammaHamza/Visual-Programming
|
/mathematicalfunc/Program.cs
| 3.359375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mathematicalfunc
{
class Program
{
public static void func1()
{
int num = 0;
int power = 0;
Console.WriteLine("enter number");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter Power");
power = Convert.ToInt32(Console.ReadLine());
double i = Math.Pow(num, power);
Console.WriteLine(i);
}
static void Main(string[] args)
{
//func1();
int[][] jagg=new int[10][];
jagg[0] = new int[]{1,2,3,4,5,6,};
jagg[5]=new int[]{2};
Console.WriteLine("jagged"+jagg);
}
}
}
|
a58f189375a9c90d5902fae9a323d07d0ecceeaa
|
C#
|
hujgup/DiscordApi
|
/Echo.Utils/IReadOnlyDictionaryExtensions.cs
| 2.640625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Echo.Utils {
// ReSharper disable once InconsistentNaming
public static class IReadOnlyDictionaryExtensions {
public static bool ContainsValue<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dic, [CanBeNull] TValue value) {
return dic.Values.Contains(value);
}
}
}
|
0a7f2de7588926580f6b82eb7ed25eb35855d276
|
C#
|
borealwinter/simpl
|
/SIMPL_DAL/Enums/EnumExtension.cs
| 3.53125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace SIMPL.DAL.Enums
{
public static class EnumExtension
{
/// <summary>
/// Contains Enum Type and dictionary containing enum value and it's string value.
/// </summary>
private static readonly IDictionary<Type, IDictionary<Enum, string>> Enums =
new Dictionary<Type, IDictionary<Enum, string>>();
/// <summary>
/// Parses Enum and populates dictionary containing Enum Type and dictionary containing enum value and it's string value
/// </summary>
private static void Init(Type enumType)
{
var values = Enum.GetValues(enumType);
IDictionary<Enum, string> hashtable = (from Enum value in values.OfType<Enum>()
let fieldInfo = enumType.GetField(value.ToString())
let attribs = fieldInfo.GetCustomAttributes(typeof(EnumStringValueAttribute), false) as EnumStringValueAttribute[]
select new
{
Key = value,
Value = attribs.Length > 0 ? attribs[0].StringValue : null
})
.ToDictionary(l => l.Key, l => l.Value);
Enums[enumType] = hashtable;
}
/// <summary>
/// An extension method which returns string value of a Enum.
/// </summary>
/// <returns>string value of Enum</returns>
public static string GetStringValue(this Enum value)
{
Type type = value.GetType();
var fieldInfo = type.GetField(value.ToString());
var attribs = fieldInfo.GetCustomAttributes(typeof(EnumStringValueAttribute), false) as EnumStringValueAttribute[];
return attribs != null && attribs.Length > 0 ? attribs.First().StringValue : value.ToString();
}
/// <summary>
/// Converts string into Enum value.
/// </summary>
/// <param name="value">string to be converted</param>
/// <param name="enumType"></param>
public static Enum Convert(string value, Type enumType)
{
var matchingEnum = (from Enum e in Enum.GetValues(enumType)
where e.GetStringValue().Equals(value, StringComparison.InvariantCultureIgnoreCase)
select e).ToList().FirstOrDefault();
if (null == matchingEnum)
{
throw new ArgumentException(string.Format("Value {0} does not exist in {1}", value, enumType), "value");
}
return matchingEnum;
}
}
}
|
68806c9094d47b68afe180a6291bcea4cdc1afe0
|
C#
|
matiascc/TP4
|
/Ej2_Test/MatematicaTest.cs
| 2.90625
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ej2;
namespace Ej2_Test
{
[TestClass]
public class MatematicaTest
{
[TestMethod]
public void TestDividir1()
{
double mDividendo = 50;
double mDivisor = 10;
double mResultadoEsperado = 5;
double mResultado;
Matematica mat = new Matematica();
mResultado = mat.Dividir(mDividendo, mDivisor);
Assert.AreEqual(mResultadoEsperado, mResultado); //Si los resultados son iguales, el test es exitoso.
}
[TestMethod]
public void TestDividir2()
{
double mDividendo = 5;
double mDivisor = 2;
double mResultadoEsperado = 2.5;
double mResultado;
Ej2.Matematica mat = new Ej2.Matematica();
mResultado = mat.Dividir(mDividendo, mDivisor);
Assert.AreEqual(mResultadoEsperado, mResultado); //Si los resultados son iguales, el test es exitoso.
}
[TestMethod]
public void TestDividir3()
{
double mDividendo = 10;
double mDivisor = 20;
double mResultadoEsperado = 0.5;
double mResultado;
Ej2.Matematica mat = new Ej2.Matematica();
mResultado = mat.Dividir(mDividendo, mDivisor);
Assert.AreEqual(mResultadoEsperado, mResultado); //Si los resultados son iguales, el test es exitoso.
}
[TestMethod]
[ExpectedException(typeof(DivisionPorCeroException))] //Se espera una excepcion de la clase DivisionPorCeroException.
public void TestDividir4()
{
double mDividendo = 5;
double mDivisor = 0;
Ej2.Matematica mat = new Ej2.Matematica();
mat.Dividir(mDividendo, mDivisor);
}
}
}
|
c04677a8e6fb9b7a134ef72c816e2a0994673b60
|
C#
|
ForestFox1997/Programming
|
/Наследование и полиморфизм/Form_Width.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Наследование_и_полиморфизм.Application_logic;
namespace Наследование_и_полиморфизм
{
public partial class Form_Width : Form
{
public Form_Width()
{
InitializeComponent();
}
private void Form_Width_FormClosing(object sender, FormClosingEventArgs e)
{
if (DialogResult == DialogResult.OK)
{
try
{
Check_arguments(textBox_n);
Check_arguments(textBox_k);
Check_arguments(textBox_d);
}
catch (FormatException E)
{
e.Cancel = true;
MessageBox.Show(E.Message, "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception E)
{
e.Cancel = true;
MessageBox.Show(E.Message, "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
|
c3c8ea749d5be743a10aaa6ee0d43bb56298fb1a
|
C#
|
Lambert-M/MakeMyQuiz
|
/Assets/Data/RoundData.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class RoundData {
//manche 1 , blindtest ...
public string Type { get; set; }
public bool IsBuzzRound { get; set; }
public List<TopicData> Topics { get; set; }
public RoundData(string type, List<TopicData> topics,bool isBuzzRound)
{
IsBuzzRound = isBuzzRound;
Type = type;
Topics = topics;
}
public int SearchTopic(string theme)
{
int index=-1;
for (int i = 0; i < Topics.Count; i++)
{
if (theme.Equals(Topics[i].Name))
{
index = i;
}
}
return index;
}
}
|
3bfe2ef683108d1a604e2db2468786a615574411
|
C#
|
Rowen0331/Weather.Coding.Challenge
|
/Coding.Challenge/Weather.Coding.Challenge/ConsoleWriter.cs
| 3.265625
| 3
|
using System;
using System.Linq;
using Weather.Coding.Challenge.Services.Model;
namespace Weather.Coding.Challenge
{
public static class ConsoleWriter
{
public static void ExitApplication()
{
Console.WriteLine("Press any key to exit application..");
Console.ReadLine();
}
public static void PrintOutput(WeatherResponse response)
{
//Check if should I go outside?
Console.WriteLine("Should I go outside?");
bool isShouldGoOutside = response.Current.Wind_Speed > 15 && !response.Current.Weather_Descriptions.Any(a => a.ToLower().Contains("rain"));
Console.WriteLine(isShouldGoOutside ? "Yes" : "No");
//Check if should I wear sunscreen?
Console.WriteLine("Should I wear sunscreen?");
bool isShouldWearSunScreen = !response.Current.Weather_Descriptions.Any(a => a.ToLower().Contains("rain"));
Console.WriteLine(isShouldWearSunScreen ? "Yes" : "No");
//Check if can I fly my kite?
Console.WriteLine("Can I fly my kite?");
bool isCanIFlyKite = response.Current.Uv_Index > 3;
Console.WriteLine(isCanIFlyKite ? "Yes" : "No");
}
public static string InputAndReadZipCode()
{
Console.Write("Please input zipcode: ");
string zipCode = Console.ReadLine();
return zipCode;
}
}
}
|
acad8dfaa844a1e033187dc4f0abd777eef6180d
|
C#
|
bopopescu/Coding-Dojo-assignments
|
/netCore/Entity_Framework/exam_2/Models/ErrorViewModel.cs
| 2.90625
| 3
|
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
/*
dotnet ef database update
dotnet ef migrations add -name
commands for migrating and updating database!
*/
namespace login_registration.Models
{
/*
regex string....
([a-zA-Z]+)([0-9]+)([!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+)
*/
public class User
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(105, MinimumLength = 2, ErrorMessage = "field must be atleast 2 and less than 105")]
public string Name { get; set; }
[Required]
[StringLength(105, MinimumLength = 2, ErrorMessage = "field must be atleast 2 and less than 105")]
public string Alias { get; set; }
[Required]
[UniqueEmail]
[RegularExpression("^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z]+$", ErrorMessage="Please enter a valid email")]
public string Email { get; set; }
[Required]
[StringLength(105, MinimumLength = 8, ErrorMessage = "field must be atleast 8 and less than 105")]
public string Password { get; set; }
public List<Post> PostsCreated {get; set;}
public User()
{
PostsCreated = new List<Post>();
}
}
public class Post
{
[Key]
public int PostId{get; set;}
[Required]
[StringLength(105, MinimumLength = 2, ErrorMessage = "field must be atleast 2 and less than 105")]
public string Description{get;set;}
public User creator {get; set;}
public List<Like> Likes {get;set;}
public Post()
{
Likes = new List<Like>();
}
}
public class Like
{
[Key]
public int LikeId {get; set;}
public int PostId {get; set;}
public Post post {get; set;}
public int UserId {get; set;}
public User user {get; set;}
}
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
|
e8faba3b46464ddb0c84e5654299a0e42b09177e
|
C#
|
PaulZero/OctopusApi
|
/OctopusApi.Client/Responses/GetConsumptionResult.cs
| 2.8125
| 3
|
using OctopusApi.Consumption;
using System;
using System.Linq;
namespace OctopusApi.Client.Responses
{
public class GetConsumptionResult
{
public bool HasItems => Items.Length > 0;
public ConsumptionUnit Unit { get; set; }
public ConsumptionItem[] Items
{
get => _items;
set {
_items = value ?? Array.Empty<ConsumptionItem>();
Refresh();
}
}
public DateTime Start { get; private set; }
public DateTime End { get; private set; }
public double TotalConsumption { get; private set; }
private ConsumptionItem[] _items = Array.Empty<ConsumptionItem>();
private void Refresh()
{
Start = default;
End = default;
TotalConsumption = default;
if (HasItems)
{
Start = Items.Min(i => i.IntervalStart);
End = Items.Max(i => i.IntervalEnd);
TotalConsumption = Items.Sum(i => i.Consumption);
}
}
}
}
|
8b1b65500607962a4a566057842304ad3eb14ed4
|
C#
|
anarki2600/lessons3
|
/lesson3.1/Program.cs
| 3.828125
| 4
|
using System;
namespace lesson3._1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите размер матрицы");
int matrix = int.Parse(Console.ReadLine()); /* Число из string преобразовываем в int и создаем переменную matrix
с этим значением*/
int k = 0; // Счётчик;
int[,] mas = new int[matrix, matrix]; // Создаем двумерный массив;
Random random = new Random();
for (int i = 0; i < matrix; i++) /*Цикл, проходящий по строкам; Инициализатор i=0, Условие i<matrix, Итератор i++
*/
{
for (int j = 0; j < matrix; j++) //Цикл, проходящий по столбцам;
{
if (i == j) mas[i, j] = k; //Заполнятся будут те элементы,номера строк и столбцов которых равны(Диагональ).
k = random.Next(100); // Уже после определения нужного элемента массива, вносим в него рандомное число 0т 0 до 100;
Console.Write(mas[i, j] + " "); //Вывод вдоль строки.
}
k++; //Увеличение переменной на 1.
Console.WriteLine(); //Переход на новую строку после заполнения предыдущей.
}
Console.ReadKey();
}
}
}
|
fbacf84c4ce2fe1f2b7ebff56b786ef5e93bac8f
|
C#
|
abaranauskas/Object-Oriented-Programming-Fundamentals-in-C-Sharp
|
/acme.Common.Test/StringHandlerTest.cs
| 2.5625
| 3
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Acme.Common;
namespace acme.Common.Test
{
[TestClass]
public class StringHandlerTest
{
[TestMethod]
public void InsertSpacesTestValid()
{
string source = " SonicScrewdriver";
string expected = "Sonic Screwdriver";
Assert.AreEqual(expected, StringHandler.InsertSpaces(source));
}
[TestMethod]
public void InsertSpacesTestWithExistigSpace()
{
string source = "Sonic Screwdriver";
string expected = "Sonic Screwdriver";
Assert.AreEqual(expected, source.InsertSpaces());
}
}
}
|
c319daa590410555467375a1cf56f2a04813cf9b
|
C#
|
SwastikDevendra/VirtualizingUniformGrid
|
/VirtualizingUniformGrid/CollectionToBind.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace VirtualizingUniformGrid
{
public class CollectionToBind : INotifyPropertyChanged
{
private ObservableCollection<Student> students;
public ObservableCollection<Student> StudentList
{
get { return students; }
set
{
students = value;
OnPropertyChanged();
}
}
public CollectionToBind()
{
Student studentObj;
StudentList = new ObservableCollection<Student>();
Random randomObj = new Random();
for (int i = 0; i < 37; i++)
{
studentObj = new Student();
studentObj.FirstName = "First " + i;
studentObj.MiddleName = "Middle " + i;
studentObj.LastName = "Last " + i;
studentObj.Photo = @"D:\Projects\VirtualizingUniformGrid\VirtualizingUniformGrid\imoticon.png";
studentObj.Age = (uint)randomObj.Next(15, 80);
StudentList.Add(studentObj);
}
OnPropertyChanged(nameof(StudentList));
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string prop = null)
{
if (PropertyChanged != null)
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(prop));
}
}
public class Student
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public uint Age { get; set; }
public string Photo { get; set; }
}
}
|
973cae32c437c04ba9a9581745477d216514a95b
|
C#
|
adrielleAm/PortalCorreios
|
/Portal Correios BackEnd/PortalCorreios.Business/EncomendaBusiness.cs
| 2.578125
| 3
|
using Microsoft.AspNetCore.Http;
using PortalCorreios.Domain.Dto;
using PortalCorreios.Interface.Business;
using PortalCorreios.Utils.BusinessException;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PortalCorreios.Business
{
public class EncomendaBusiness : IEncomendaBusiness
{
private readonly IArquivoBusiness _arquivoBusiness;
private readonly ITrechosBusiness _trechosBusiness;
public EncomendaBusiness(IArquivoBusiness arquivoBusiness, ITrechosBusiness trechosBusiness)
{
_arquivoBusiness = arquivoBusiness;
_trechosBusiness = trechosBusiness;
}
public async Task<List<string>> CalcularEncomenda(IFormFile arquivo)
{
var trechos = await _trechosBusiness.RecuperarTrechos();
var encomendasString = await _arquivoBusiness.LerLinhasArquivo(arquivo);
var encomendasDto = ConvertToDto(encomendasString);
List<string> caminhoEncomendas = new List<string>();
foreach (var dto in encomendasDto)
caminhoEncomendas.Add(RecuperarMenorRecurso(dto, trechos));
return caminhoEncomendas;
}
private string RecuperarMenorRecurso(EncomendaDto encomenda, List<TrechoDto> trechos)
{
var menorRecurso = new StringBuilder();
int soma = 0;
menorRecurso.Append($"{encomenda.Origem} ");
var origem = trechos.Where(c => c.Origem == encomenda.Origem).ToList();
var destinos = trechos.Where(c => c.Destino == encomenda.Destino).ToList();
var linha = origem.FirstOrDefault(o => o.Destino == encomenda.Destino);
if (linha != null)
menorRecurso.Append($"{encomenda.Destino} {linha.TempoViagem}");
else
{
var listaFinal = origem.Concat(destinos).ToList();
foreach (var item in listaFinal)
{
if (item.Destino == encomenda.Destino)
{
menorRecurso.Append($"{item.Origem} ");
soma += item.TempoViagem + origem.FirstOrDefault(c => c.Destino == item.Origem).TempoViagem;
}
};
}
menorRecurso.Append($"{encomenda.Destino} {soma.ToString()} ");
return menorRecurso.ToString();
}
private List<EncomendaDto> ConvertToDto(List<string> encomendas)
{
var encomndasList = new List<EncomendaDto>();
foreach (var encomenda in encomendas)
{
string[] values = encomenda.Split(' ').Select(sValue => sValue.Trim()).ToArray();
if (values.Length >= 2)
encomndasList.Add(new EncomendaDto { Origem = values[0], Destino = values[1] });
}
return encomndasList;
}
}
}
|
2bd125deb5dcaa45594a1f5db14c678362a3cda4
|
C#
|
RicardinhoFilho/CSharp-Varied-Examples
|
/Exemplos _Variados/AdicionandoExtesõesAClasseListGenerica/ListExtensoens.cs
| 3.375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AdicionandoExtesõesAClasseListGenerica
{
public static class ListExtensoens
{
/// <summary>
/// Método genérico "T" que facilita a ad~ção de itens em nossa lista
/// </summary>
/// <typeparam name="T">Tipo Genérico</typeparam>
/// <param name="listaDeInteiros"></param>
/// <param name="itens"></param>
public static void AdicionarVarios<T>(this List<T> listaDeInteiros, params T[] itens)
{
foreach (T item in itens)
{
listaDeInteiros.Add(item);
}
}
/// <summary>
/// Método que escreve na tela nossa lista genérica
/// </summary>
/// <typeparam name="T">Tipo genérico</typeparam>
/// <param name="listaDeInteiros"></param>
public static void EscreveListaNaTela<T>(this List<T> listaDeInteiros)
{
foreach (T item in listaDeInteiros)
{
Console.WriteLine(item);
}
}
}
}
|
c8a495f40fca9a5bc5aec2ca74000fac8d531fe2
|
C#
|
JulianVolodia/wincompose
|
/src/composer/Log.cs
| 2.59375
| 3
|
//
// WinCompose — a compose key for Windows — http://wincompose.info/
//
// Copyright © 2013—2018 Sam Hocevar <sam@hocevar.net>
// 2014—2015 Benjamin Litzelmann
//
// This program is free software. It comes without any warranty, to
// the extent permitted by applicable law. You can redistribute it
// and/or modify it under the terms of the Do What the Fuck You Want
// to Public License, Version 2, as published by the WTFPL Task Force.
// See http://www.wtfpl.net/ for more details.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading;
using System.Windows.Threading;
namespace WinCompose
{
public class LogEntry
{
public DateTime DateTime { get; set; }
public string Message { get; set; }
}
public class LogList : ObservableCollection<LogEntry>
{
// Override the CollectionChanged event so that we can track listeners and call
// their delegates in the correct thread.
// FIXME: would a Log.MessageReceived event be more elegant?
public override event NotifyCollectionChangedEventHandler CollectionChanged
{
add
{
if (Dispatcher.CurrentDispatcher.Thread.GetApartmentState() == System.Threading.ApartmentState.STA)
PreferredDispatcher = Dispatcher.CurrentDispatcher;
ListenerCount += value?.GetInvocationList().Length ?? 0;
base.CollectionChanged += value;
}
remove
{
base.CollectionChanged -= value;
ListenerCount -= value?.GetInvocationList().Length ?? 0;
}
}
public Dispatcher PreferredDispatcher = Dispatcher.CurrentDispatcher;
public int ListenerCount { get; set; }
}
public static class Log
{
private static LogList m_entries = new LogList();
public static LogList Entries => m_entries;
#if DEBUG
static Log()
{
m_entries.CollectionChanged += ConsoleDebug;
}
private static void ConsoleDebug(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (LogEntry entry in e.NewItems)
{
string msgf = $"{entry.DateTime:yyyy/MM/dd HH:mm:ss.fff} {entry.Message}";
System.Diagnostics.Debug.WriteLine(msgf);
}
}
}
#endif
public static void Debug(string format, params object[] args)
{
// We don’t do anything unless we have listeners
if (m_entries.ListenerCount > 0)
{
DateTime date = DateTime.Now;
var msg = string.Format(format, args);
ThreadPool.QueueUserWorkItem(x =>
{
m_entries.PreferredDispatcher.Invoke(DispatcherPriority.Background, DebugSTA, date, msg);
});
}
}
private delegate void DebugDelegate(DateTime date, string msg);
private static DebugDelegate DebugSTA = (date, msg) =>
{
var entry = new LogEntry() { DateTime = date, Message = msg };
while (m_entries.Count > 1024)
m_entries.RemoveAt(0);
m_entries.Add(entry);
};
}
}
|
85d01066ce7b6e0d5c9b8fcdf8e7a24ae94724eb
|
C#
|
ayushkumarsinha/Zilon_Roguelike
|
/Zilon.Core/Zilon.Core/Scoring/IPlayerEventLogService.cs
| 2.53125
| 3
|
using Zilon.Core.Tactics;
namespace Zilon.Core.Scoring
{
/// <summary>
/// Сервис для логирования событий, связанных с персонажем игрока
/// </summary>
public interface IPlayerEventLogService
{
/// <summary>
/// Зафиксировать событие.
/// </summary>
/// <param name="playerEvent"></param>
void Log(IPlayerEvent playerEvent);
/// <summary>
/// Актёр игрока.
/// </summary>
IActor Actor { get; set; }
/// <summary>
/// Вернуть последнее зарегистрированние событие.
/// </summary>
/// <returns></returns>
IPlayerEvent GetPlayerEvent();
}
}
|
799c3f9d12315e1279973bf44c7fd37d02bed577
|
C#
|
Boydbueno/Hondenstreken
|
/HondenStreken/HondenStreken/Classes/Graphics/Overlay/Cursor.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace HondenStreken
{
class Cursor : MouseGameElement
{
#region Constructors
/// <summary>
/// To create a cursor that follows the mouse
/// </summary>
public Cursor(Game game, Texture2D texture)
: base(game, texture, Vector2.Zero)
{
}
#endregion
#region Methods
public override void Update(GameTime gameTime)
{
FollowMouse();
}
#endregion
}
}
|
d70986ed048dba150bd3a63d184eccbca69d1521
|
C#
|
DotNet-projects-UCaldas/Proyecto_Software_II_BlastCode_2021_01
|
/Aplicacion/AppCore/AccesoDatos/DAOs/MesaDAO.cs
| 2.640625
| 3
|
using AccesoDatos.Interfaces;
using AccesoDatos.Modelos;
using AccesoDatos.Repositorios;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AccesoDatos.DAOs
{
/// <summary>
/// Clase Data Access Object para gestionar la Clase MesaModelo
/// </summary>
public class MesaDAO : IRepositorioMesa
{
private readonly RepositorioMesas _repoMesas = new RepositorioMesas();
/// <summary>
/// Método para agregar una nueva mesa
/// </summary>
/// <param name="nuevaMesa">Mesa a agregar</param>
/// <returns>Mesa agregada</returns>
public MesaModel AgregarMesa(MesaModel nuevaMesa)
{
MesaModel mesaGuardada = _repoMesas.AgregarMesa(nuevaMesa);
return mesaGuardada;
}
/// <summary>
/// Método para guardar una mesa editada
/// </summary>
/// <param name="mesa">Mesa editada</param>
/// <returns>Mesa editada</returns>
public MesaModel EditarMesa(MesaModel mesa)
{
MesaModel mesaEditada = _repoMesas.EditarMesa(mesa);
return mesaEditada;
}
/// <summary>
/// Método para eliminar una mesa
/// </summary>
/// <param name="Id">Id de la mesa a eliminar</param>
/// <returns></returns>
public MesaModel EliminarMesa(string Id)
{
MesaModel mesaEliminada = _repoMesas.EliminarMesa(Id);
return mesaEliminada;
}
/// <summary>
/// Método que retorna las mesas
/// </summary>
/// <returns>Lista de mesas MesaModel</returns>
public List<MesaModel> ListarMesas()
{
return _repoMesas.ListarMesas();
}
}
}
|
eb37b35f44c1764ea95d9ad089bbf6007b62b07a
|
C#
|
rakeshdangar/DataStructure
|
/MatrixRectangleCoOrdinates.cs
| 3.90625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class MatrixRectangleCoOrdinates
{
// Imagine we have an image. We’ll represent this image as a simple 2D array where every pixel is a 1 or a 0. The image you get is known to have a single rectangle of 0s on a background of 1s. Write a function that takes in the image and returns the coordinates of the rectangle -- either top-left and bottom-right; or top-left, width, and height.
// {x: 3, y: 2, width: 3, height: 2}
// [[2,3],[3,5]]
// [[3,2],[5,3]] //same answer, just with reversed columns/rows
// {y1: 2, x1: 3, y2: 3, x2: 5}
// [2, 3, 3, 5]
// “2 3 3 5”
public static void Init()
{
int[][] image = new int[][]
{
new int[] {1, 1, 1, 1, 1, 1, 0},
new int[] {1, 1, 1, 1, 1, 1, 0},
new int[] {1, 1, 1, 1, 1, 1, 0},
new int[] {1, 1, 1, 1, 1, 1, 1},
new int[] {1, 1, 1, 1, 1, 1, 1}
};
Console.WriteLine(FindCoordinates(image));
}
private static string FindCoordinates(int[][] image)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < image.GetLength(0); i++)
{
for (int j = 0; j < image[i].Length; j++)
{
if (image[i][j] == 0)
{
//store the first coordinates
sb.AppendLine("x:" + j.ToString() + ", y:" + i.ToString());
//Get second coordinates.
if(i==image.GetLength(0)-1 && j==image[i].Length-1)
sb.Append("x:" + j.ToString() + ", y:" + i.ToString());
else
sb.Append(FindSecondCo(image, i, j));
return sb.ToString();
}
}
}
return string.Empty;
}
private static string FindSecondCo(int[][] image, int y, int x)
{
StringBuilder sb = new StringBuilder();
for (int i = y; i < image.GetLength(0); i++)
{
for (int j = x; j < image[i].Length; j++)
{
if (image[i][j] == 0)
{
y = i;
x = j;
}
else
break;
}
}
sb.Append("x:" + (x).ToString() + ", y:" + y.ToString());
return sb.ToString();
}
}
}
|
292be94b0d8f9551673039a6aae5700605e9e2ab
|
C#
|
MissPeperr/Heist
|
/LockSpecialist.cs
| 3.078125
| 3
|
using System;
namespace adams_exercise
{
public class LockSpecialist : IRobber
{
public string Name { get; set; }
public int SkillLevel { get; set; }
public int PercentageCut { get; set; }
public void PerformSkill(Bank Bank)
{
Console.WriteLine($"{Name} is cracking the vault. Decreased vault score by {SkillLevel} points.");
if (Bank.VaultScore <= 0)
{
Console.WriteLine($"{Name} has cracked the vault!");
}
else
{
Bank.VaultScore = Bank.VaultScore - SkillLevel;
}
}
}
}
|
381e8bab1e5c1ae28788d4303768c74f9eb93cdb
|
C#
|
abjerner/Skybrud.Social.BitBucket
|
/src/Skybrud.Social.BitBucket/Models/Users/BitBucketUserLinkCollection.cs
| 2.53125
| 3
|
using Newtonsoft.Json.Linq;
namespace Skybrud.Social.BitBucket.Models.Users {
/// <summary>
/// Class representing the <code>links</code> object/collection of a BitBucket user.
/// </summary>
public class BitBucketUserLinkCollection : BitBucketLinkCollection {
#region Properties
public BitBucketLink Hooks { get; private set; }
public BitBucketLink Self { get; private set; }
public BitBucketLink Repositories { get; private set; }
public BitBucketLink Html { get; private set; }
public BitBucketLink Followers { get; private set; }
public BitBucketLink Avatar { get; private set; }
public BitBucketLink Following { get; private set; }
public BitBucketLink Snippets { get; private set; }
#endregion
#region Constructors
private BitBucketUserLinkCollection(JObject obj) : base(obj) {
Hooks = GetLink("hooks");
Self = GetLink("self");
Repositories = GetLink("repositories");
Html = GetLink("html");
Followers = GetLink("followers");
Avatar = GetLink("avatar");
Following = GetLink("following");
Snippets = GetLink("snippets");
}
#endregion
#region Static methods
/// <summary>
/// Parses the specified <code>obj</code> into an instance of <see cref="BitBucketUserLinkCollection"/>.
/// </summary>
/// <param name="obj">The instance of <see cref="JObject"/> to be parsed.</param>
/// <returns>Returns an instance of <see cref="BitBucketUserLinkCollection"/>.</returns>
public new static BitBucketUserLinkCollection Parse(JObject obj) {
return obj == null ? null : new BitBucketUserLinkCollection(obj);
}
#endregion
}
}
|
27c9c98028eb008bd31f8a70b6e233751160061f
|
C#
|
rajeshwarn/racer
|
/51Racer/ADBHelper.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _51Racer
{
class ADBHelper
{
private string exePath;
private static object lockHelper = new object();
private static ADBHelper instance = null;
private ADBHelper(string exePath)
{
this.exePath = exePath;
EnvInfo.StartProcess(exePath, "fork-server server", false);
}
public static ADBHelper GetShareInstance()
{
if (instance.exePath != null)
return GetShareInstance(instance.exePath);
else
return null;
}
public static ADBHelper GetShareInstance(string exePath)
{
lock (lockHelper)
{
if (instance == null)
instance = new ADBHelper(exePath);
return instance;
}
}
private string SendMessage(string message)
{
return EnvInfo.StartProcess(exePath, message);
}
private string SendMessage(string device, string message)
{
message = "-s "+device+" "+message;
return SendMessage(message);
}
public AndoridDevice[] ListDevice()
{
string temp = SendMessage("devices");
int index = temp.IndexOf("List of devices attached");
List<AndoridDevice> list = new List<AndoridDevice>();
if (index >= 0)
{
temp = temp.Substring(index);
temp = temp.Replace("List of devices attached \r\n", "");
temp = temp.Replace("\r\n\r\n", "");
temp = temp.Replace("\r\n", "|");
if (temp.Length > 6)
{
foreach (string i in temp.Split('|'))
{
string[] temp2 = i.Split('\t');
AndoridDeviceStatus status = AndoridDeviceStatus.OnLine;
if (temp2.Length > 1 && temp2[1] != "device")
status = AndoridDeviceStatus.OffLine;
list.Add(new AndoridDevice(temp2[0], status));
}
}
}
return list.ToArray();
}
public bool InstallApp(string device, string appPath)
{
string message = "install -r \"" + appPath + "\"";
if (SendMessage(device, message).ToLower().IndexOf("success") >= 0)
return true;
return false;
}
}
}
|
baf0022b9853be245aab737024686dcd44429ad2
|
C#
|
auth0-blog/xamarin-todo
|
/Todo/Repositories/MemoryDataRepository.cs
| 3.453125
| 3
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Todo.Models;
using Xamarin.Forms;
using System.Linq;
namespace Todo.Repositories
{
/// <summary>
/// A data repository that marshals Todo items between the app and the API
/// </summary>
public class MemoryDataRepository : IDataRepository
{
private List<TodoItem> items;
private int nextId;
public MemoryDataRepository()
{
items = new List<TodoItem>
{
new TodoItem { Id = 1, Title = "Finish building that cat GIF app" },
new TodoItem { Id = 2, Title = "Wash the car" },
new TodoItem { Id = 3, Title = "Lunch meeting with colleagues", IsDone = true }
};
SetNextId();
}
/// <summary>
/// Gets the Todo item data
/// </summary>
public Task<IEnumerable<TodoItem>> GetData()
{
return Task.FromResult(items.Select(i => i.Clone() as TodoItem).OrderBy(i => i.IsDone).AsEnumerable());
}
/// <summary>
/// Removes the specified item from the data set
/// </summary>
public Task<IEnumerable<TodoItem>> RemoveItem(TodoItem item)
{
items.Remove(item);
return GetData();
}
/// <summary>
/// Adds a new item to the collection
/// </summary>
/// <param name="item">The item to add</param>
public Task<IEnumerable<TodoItem>> AddItem(TodoItem item)
{
items.Add(item);
SetNextId();
return GetData();
}
/// <summary>
/// Updates the item in the list
/// </summary>
public Task<IEnumerable<TodoItem>> UpdateItem(TodoItem item)
{
var existingItem = items.FirstOrDefault(i => i.Id == item.Id);
if (existingItem != null)
{
existingItem.Title = item.Title;
existingItem.IsDone = item.IsDone;
}
return GetData();
}
/// <summary>
/// Figures out what the next item ID should be
/// </summary>
private void SetNextId()
{
nextId = items.Max(i => i.Id) + 1;
}
}
}
|
53c711b29d9ac5778cfdbef2b5555394c76ec271
|
C#
|
Nelson-Chacon/Ventas
|
/Ventas_Proyecto/BL.Ventas/NiñosBL.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BL.Ventas
{
public class NiñosBL
{
Contexto _contexto;
public BindingList<Niños> ListaProdNiños { get; set; }
public NiñosBL()
{
_contexto = new Contexto();
ListaProdNiños = new BindingList<Niños>(); //Instanciar
}
public BindingList<Niños> ObtenerProductos()
{
_contexto.Niño.Load();
ListaProdNiños = _contexto.Niño.Local.ToBindingList();
return ListaProdNiños;
}
public ResultadoNiños GuardarProdNiños(Niños niños)
{
var resultadoNiños = Validar(niños);
if (resultadoNiños.Exitoso == false)
{
return resultadoNiños;
}
_contexto.SaveChanges();
resultadoNiños.Exitoso = true;
return resultadoNiños;
}
public void AgregarProdNiños()
{
var nuevoProdNiños = new Niños();
ListaProdNiños.Add(nuevoProdNiños);//se agrega un nuevo producto a la lista
}
public bool EliminarProdNiños(int id)
{
foreach (var prodNiño in ListaProdNiños)//recorre la lista de los objetos
{
if (prodNiño.Id==id)
{
ListaProdNiños.Remove(prodNiño);
return true;
}
}
return false;
}
private ResultadoNiños Validar(Niños niños)
{
var resultadoNiños = new ResultadoNiños();
resultadoNiños.Exitoso = true;
if(string.IsNullOrEmpty(niños.Descripcion)==true)
{
resultadoNiños.Mensaje = "Ingrese una descripcion";
resultadoNiños.Exitoso = false;
}
if (string.IsNullOrEmpty(niños.Seccion) == true)
{
resultadoNiños.Mensaje = "Ingrese la seccion";
resultadoNiños.Exitoso = false;
}
if (niños.Existencia <0)
{
resultadoNiños.Mensaje = "La existencia debe ser mayor que cero";
resultadoNiños.Exitoso = false;
}
if (niños.Precio < 0)
{
resultadoNiños.Mensaje = "El precio debe ser mayor que cero";
resultadoNiños.Exitoso = false;
}
return resultadoNiños;
}
}
public class Niños
{
public int Id { get; set; }
public string Descripcion { get; set; }
public double Precio { get; set; }
public string Seccion { get; set; }
public int Existencia { get; set; }
public byte[] Foto { get; set; }
public bool Activo { get; set; }
}
public class ResultadoNiños:ResultadoMujer
{
}
}
|
a31978e31c75ab023f580425a0d2021f1fbb5690
|
C#
|
LeonmDK3/Mary
|
/Lib/InSimDotNet/Packets/FlagType.cs
| 2.515625
| 3
|
namespace InSimDotNet.Packets
{
/// <summary>
/// Represents the <see cref="IS_FLG"/> Flag.
/// </summary>
public enum FlagType
{
/// <summary>
/// No flag shown.
/// </summary>
None,
/// <summary>
/// Blue flag (car being lapped).
/// </summary>
Blue,
/// <summary>
/// Yellow flag (car is slow or stopped in dangerous place).
/// </summary>
Yellow,
}
}
|
be9f44765e03730933b61bb5158738918cbdf127
|
C#
|
dimitriosweb/api-net-core
|
/CityInfo/CityInfo.API/CitiesDataStore.cs
| 2.625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CityInfo.API.Models;
namespace CityInfo.API
{
public class CitiesDataStore
{
public static CitiesDataStore Current { get; } = new CitiesDataStore();
public List<CityDto> Cities { get; set; }
public CitiesDataStore()
{
Cities = new List<CityDto>
{
new CityDto
{
Id = 1,
Name = "New York City",
Description = "NYC Desc",
PointsOfInterest = new List<PointsOfInterestDto>()
{
new PointsOfInterestDto()
{
Id = 1,
Name = "Central Park",
Description = "Central Park Description"
},
new PointsOfInterestDto()
{
Id = 2,
Name = "Empire State Building",
Description = "Description Empire State Building"
}
}
},
new CityDto
{
Id = 2,
Name = "Athens",
Description = "Athens Desc",
PointsOfInterest = new List<PointsOfInterestDto>()
{
new PointsOfInterestDto()
{
Id = 4,
Name = "Acropolis",
Description = "Description Acropolis"
}
}
},
new CityDto
{
Id = 3,
Name = "Zurich",
Description = "Zurich Desc"
}
};
}
}
}
|
49798f4443e9e3553ecc98a4f96bfbcecb4d0025
|
C#
|
chrissar/MechFactorXXL
|
/Blayne/Assets/Scripts/AI/Commands/ChangeFireTeamFormationCommand.cs
| 2.515625
| 3
|
using System;
using UnityEngine;
public class ChangeFireTeamFormationCommand : Command
{
public FireTeamFormation mFireTeamFormation;
public ChangeFireTeamFormationCommand ()
{
mFireTeamFormation = FireTeamFormation.WEDGE;
}
public ChangeFireTeamFormationCommand (FireTeamFormation formation)
{
mFireTeamFormation = formation;
}
public override void execute(Ally ally)
{
if (ally != null && ally is FireTeam)
{
FireTeam fireTeam = ally as FireTeam;
// Set the formation of the ally's fire team to the wedge formation.
fireTeam.SetFormation(mFireTeamFormation);
// Set the fire team members to the move state.
for (int i = 0; i < FireTeam.kMaxFireTeamMembers; ++i) {
FireTeamAlly allyAtSlot = fireTeam.GetAllyAtSlotPosition (i);
if (allyAtSlot != null) {
allyAtSlot.StateMachine.currentMovementState.ToMoving ();
}
}
}
}
}
|
b80d0be863af25acd98acd6318b231847804997e
|
C#
|
wangzhiqing999/my-csharp-sample
|
/P0202_DefaultAdapter/Adapter/Normal.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace P0202_DefaultAdapter.Adapter
{
public class Normal : DefaultAdapter
{
/// <summary>
/// 电话面试.
/// </summary>
public override void Test1()
{
Console.WriteLine("对于普通的嘛,先电话面试,排除掉部分......");
}
/// <summary>
/// 技术部 面试.
/// </summary>
public override void Test2()
{
Console.WriteLine("对于普通的,技术部面试,排除掉部分......");
}
/// <summary>
/// HR 面试.
/// </summary>
public override void Test3()
{
Console.WriteLine("对于普通的,HR 排除掉部分......");
}
/// <summary>
/// 笔试
/// </summary>
public override void Test4()
{
Console.WriteLine("对于普通的,笔试是不可避免的......");
}
/// <summary>
/// BOSS 面试.
/// </summary>
public override void Test5()
{
Console.WriteLine("对于普通的,老板看的顺眼是必须的......");
}
}
}
|
66a163e4d26e7b9dbc7301d88b7858b353351f2c
|
C#
|
moslem-hadi/Webtina.UI.FileShop
|
/Webtina.UI.Models/Dto/Exceptions/BadRequestException.cs
| 2.5625
| 3
|
using System;
namespace Webtina.UI.Models
{
/// <summary>
/// درخواست اشتباه
/// </summary>
public class BadRequestException : AppException
{
public BadRequestException()
: base(ApiResultStatusCode.BadRequest)
{
}
public BadRequestException(string message)
: base(ApiResultStatusCode.BadRequest, message,System.Net.HttpStatusCode.BadRequest)
{
}
public BadRequestException(object additionalData)
: base(ApiResultStatusCode.BadRequest, additionalData)
{
}
public BadRequestException(string message, object additionalData)
: base(ApiResultStatusCode.BadRequest, message, additionalData)
{
}
public BadRequestException(string message, Exception exception)
: base(ApiResultStatusCode.BadRequest, message, exception)
{
}
public BadRequestException(string message, Exception exception, object additionalData)
: base(ApiResultStatusCode.BadRequest, message, exception, additionalData)
{
}
}
}
|
01b3e68647a6c8cee195d551c8780358e7850517
|
C#
|
r2d2m/ProceduralMapGeneration
|
/Assets/Scripts/TextureGenerator.cs
| 3.265625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TextureGenerator
{
public static Texture2D TextureFromColours(Color[] colourMap, int width, int height)
{
Texture2D texture = new Texture2D(width, height);
texture.SetPixels(colourMap);
texture.filterMode = FilterMode.Point;
texture.wrapMode = TextureWrapMode.Clamp;
texture.Apply();
return texture;
}
public static Texture2D TextureFromHeightMap(float[,] heightMap)
{
int w = heightMap.GetLength(0); //the width
int h = heightMap.GetLength(1); //the height
//create a texture of the maps width and height
Texture2D texture = new Texture2D(w, h);
//generate an array of all of the colours for the pixels
Color[] colours = new Color[w * h];
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
//y*W (current row we are) x is the current index
//so, y*w+x, is our current index
colours[y * w + x] = Color.Lerp(Color.black, Color.white, heightMap[x, y]);
}
}
return TextureFromColours(colours, w, h);
}
}
|
a04650c027cff5558452b69733c7acecf73c05a3
|
C#
|
marklxie/my_firstCSharp
|
/SqlServerCSharpLib/SQLServer.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Microsoft.Data.SqlClient;
namespace SqlServerCSharpLib {
public class SQLServer {
public SqlConnection SqlConnection = null;
public List<Student> ExecuteQuery(string sql) {
var cmd = new SqlCommand(sql, SqlConnection);
var reader = cmd.ExecuteReader();
List<Student> students = new List<Student>();
while(reader.Read()) {
var student = new Student();
student.Id = Convert.ToInt32(reader["Id"]);
student.Firstname = Convert.ToString(reader["Firstname"]);
student.Lastname = Convert.ToString(reader["Lastname"]);
student.SAT = reader.IsDBNull("SAT") ? (int?)null : Convert.ToInt32(reader["SAT"]);
student.GPA = Convert.ToDecimal(reader["GPA"]);
student.MajorId = reader.IsDBNull("MajorId") ? (int?)null : Convert.ToInt32(reader["MajorId"]);
students.Add(student);
}
reader.Close();
return students;
}
public bool Connect(string server, string instance, string database) {
var connectionString = $"server={server}\\{instance};database={database};trusted_connection=true";
SqlConnection = new SqlConnection(connectionString);
SqlConnection.Open();
if(SqlConnection.State != System.Data.ConnectionState.Open) {
throw new Exception("Cannot connect to SQL");
}
return true;
}
public void Disconnect() {
if(SqlConnection == null) {
return;
}
SqlConnection.Close();
SqlConnection = null;
}
}
}
|
9161c6aec1b3c1b73f257a9f21646b22484a0061
|
C#
|
haimadrian/OOP-DotNet
|
/HW/C21 Ex03 HaimAdrian _ YakirSaadia _/Ex03.GarageLogic/Api/Vehicle/Tire.cs
| 2.96875
| 3
|
using Ex03.GarageLogic.Api.Exceptions;
using Ex03.GarageLogic.Api.Utils;
namespace Ex03.GarageLogic.Api.Vehicle
{
// Use a class and not struct cause we would like to support updating air pressure without being immutable.
// Otherwise we would have to expose an ITire interface which would then box the struct type.. so just use a class.
public class Tire
{
private readonly float r_MaxAirPressure;
private string m_ManufacturerName;
private float m_AirPressure;
public Tire(float i_MaxAirPressure, float i_AirPressure)
{
r_MaxAirPressure = i_MaxAirPressure;
m_AirPressure = i_AirPressure;
}
public string ManufacturerName
{
get
{
return m_ManufacturerName;
}
set
{
FormatValidations.ValidateAlphaNumericFormat(value, "Manufacturer Name");
m_ManufacturerName = value;
}
}
public float MaxAirPressure
{
get
{
return r_MaxAirPressure;
}
}
public float AirPressure
{
get
{
return m_AirPressure;
}
private set
{
const float k_MinAirPressure = 0;
const string k_AirPressureOutOfRangeMessage = "Air pressure is out of range. Range: [{0}, {1}], Was: {2}";
if ((value > MaxAirPressure) || (value < k_MinAirPressure))
{
throw new ValueOutOfRangeException(
string.Format(k_AirPressureOutOfRangeMessage, k_MinAirPressure, MaxAirPressure, value),
k_MinAirPressure,
MaxAirPressure);
}
m_AirPressure = value;
}
}
public void Inflate(float i_AirPressureToFill)
{
AirPressure += i_AirPressureToFill;
}
public void Deflate(float i_AirPressureToRemove)
{
Inflate(-i_AirPressureToRemove);
}
public override string ToString()
{
return string.Format("Manufacturer: {0}, Air Pressure (Actual / Max): {1} / {2}", ManufacturerName, AirPressure, MaxAirPressure);
}
}
}
|
7812dbf7db875c7a637e19ce2011fc8c560cad32
|
C#
|
com03240/Trading
|
/src/LionFire.Trading/Accounts/Positions.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace LionFire.Trading
{
public class Positions : List<Position>, IPositions
{
public event Action<PositionClosedEventArgs> Closed;
public event Action<PositionOpenedEventArgs> Opened;
public Position Find(string label, Symbol symbol)
{
return this.Where(p => p.Label == label && p.SymbolCode == symbol.Code).FirstOrDefault();
}
}
}
|
6b7e357c3033724caa5726947541e38475d46e4d
|
C#
|
dungnguyentien0409/competitive-programming
|
/C#/435. Non-overlapping Intervals.cs
| 3.09375
| 3
|
/*
* Link: https://leetcode.com/problems/non-overlapping-intervals/
* Author: Dung Nguyen Tien (Chris)
*/
public class Solution {
public int EraseOverlapIntervals(int[][] intervals) {
if (intervals.Length <= 1) return 0;
Array.Sort(intervals, delegate(int[] a, int[] b) {
return a[1] - b[1];
});
var last = intervals[0];
var count = 1;
for (var i = 1; i < intervals.Length; i++) {
var current = intervals[i];
if (current[0] >= last[1]) {
count++;;
last = current;
}
}
return intervals.Length - count;
}
}
|
92bc07f5a744789f4a7e6fda76c2d330f2fc36d5
|
C#
|
conslab/snek
|
/snek..cs
| 3.15625
| 3
|
using System;
using System.Threading;
namespace snek
{
class Program
{
public static char movement = 'r';
public static int x = 5;
public static int y = 5;
public static int length = 5;
public static int[,] a = new int[256, 2];
public static int bx;
public static int by;
public static bool bonus = true;
public static Random rand = new Random();
public static Thread t = new Thread(new ThreadStart(SnakeMovement));
static void ScorePlus()
{
length++;
bx = rand.Next(1, 15);
by = rand.Next(1, 15);
for (int i = 1; i < length; i++)
{
if (bx == a[i, 0] && by == a[i, 1])
{
ScorePlus();
length--;
}
}
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.Green;
Console.SetCursorPosition(bx * 2, by);
Console.Write(" ");
bonus = false;
}
static void Death()
{
Thread.Sleep(2000);
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Gray;
Console.Clear();
Console.SetCursorPosition(0, 0);
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine($"you killed snek.\n" +
$"why? it ate just {length - 6} green blobs. why would you do that?\n" +
$"just close the application. you are an awful person.");
}
static void SnakeMovement()
{
while (true)
{
if (bonus)
ScorePlus();
switch (movement)
{
case 'u':
y--;
break;
case 'd':
y++;
break;
case 'l':
x--;
break;
case 'r':
x++;
break;
}
Console.SetCursorPosition(x * 2, y);
Console.BackgroundColor = ConsoleColor.Cyan;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write(" ");
for (int i = length - 1; i > 0; i--)
{
a[i, 0] = a[i - 1, 0];
a[i, 1] = a[i - 1, 1];
}
a[0, 0] = x;
a[0, 1] = y;
if (x == bx && y == by)
{
bonus = true;
}
for (int i = 1; i < length; i++)
{
if (a[0, 0] == a[i, 0] && a[0, 1] == a[i, 1])
{
Death();
Thread.Sleep(int.MaxValue);
}
}
if (a[0, 0] < 1 ||
a[0, 1] < 1 ||
a[0, 0] > 15 ||
a[0, 1] > 14)
{
Death();
Thread.Sleep(int.MaxValue);
}
Console.SetCursorPosition(a[length - 2, 0] * 2, a[length - 2, 1]);
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.White;
Console.Write(" ");
Console.SetCursorPosition(0, 0);
Console.BackgroundColor = ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(" ");
Console.CursorLeft--;
Thread.Sleep(200);
}
}
static void Main(string[] args)
{
Console.WriteLine("not welcome to \"snek.\"\n" +
"this is not a snake game. this is snek.\n" +
"if you wanna start, press 'y'\n" +
"if not, just close this window or press 'n'\n" +
"maybe you want to know something about \"snek\", press 'a' for that");
bool cont = false;
while (!cont)
{
ConsoleKey k = Console.ReadKey(true).Key;
switch (k)
{
case ConsoleKey.Y:
cont = true;
break;
case ConsoleKey.N:
Console.WriteLine("ok, closing application...");
Thread.Sleep(736);
Environment.Exit(0);
break;
case ConsoleKey.A:
Console.Clear();
Console.WriteLine("in this game you are controlling snek.\n" +
"who is \"snek.\"? idk lol\n" +
"arrow keys is controlling his movement.\n" +
"you should help snek. to collect all green blobs, which makes him really long snek.\n" +
"\n\n\n" +
"if you wanna start, press 'y'\n" +
"if not, just close this window or press 'n'\n");
while (!cont)
{
ConsoleKey kk = Console.ReadKey(true).Key;
switch (kk)
{
case ConsoleKey.Y:
cont = true;
break;
case ConsoleKey.N:
Console.WriteLine("ok, closing application...");
Thread.Sleep(736);
Environment.Exit(0);
break;
default:
Console.WriteLine("wrong key... are you sure you can read?");
break;
}
}
break;
default:
Console.WriteLine("wrong key... are you sure you can read?");
break;
}
}
Console.Clear();
Console.SetWindowSize(34, 16);
//top line
Console.BackgroundColor = ConsoleColor.Red;
for (int i = 0; i < 17; i++)
{
Console.Write(" ");
}
Console.WriteLine();
//left line
for (int i = 0; i < 14; i++)
{
Console.WriteLine(" ");
}
//bottom line
for (int i = 0; i < 17; i++)
{
Console.Write(" ");
}
//right line
Console.SetCursorPosition(32, 1);
for (int i = 0; i < 16; i++)
{
Console.WriteLine(" ");
Console.SetCursorPosition(32, i + 1);
}
//field
Console.SetCursorPosition(2, 1);
Console.BackgroundColor = ConsoleColor.White;
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
Console.Write(" ");
}
Console.SetCursorPosition(2, i + 1);
}
Console.SetCursorPosition(10, 5);
t.Start();
while (true)
{
ConsoleKey c = Console.ReadKey(true).Key;
switch (c)
{
case ConsoleKey.UpArrow:
movement = 'u';
break;
case ConsoleKey.DownArrow:
movement = 'd';
break;
case ConsoleKey.LeftArrow:
movement = 'l';
break;
case ConsoleKey.RightArrow:
movement = 'r';
break;
}
}
}
}
}
|
db2552aa17b5deee1d704b97a15297fe3f397852
|
C#
|
shendongnian/download4
|
/first_version_download2/91346-6074739-13146824-4.cs
| 2.953125
| 3
|
private Dictionary<string, int> votes; // initialized in constructor
private void AddVotes(string peep, int votes)
{
if (this.votes.ContainsKey(peep)
{
this.votes[peep] += votes;
}
else
{
this.votes[peep] = votes;
}
}
|
b71220570aa3ba4c9c3dd71d20a29b8ac8eee8b1
|
C#
|
FlorianRappl/YAMP
|
/YAMP.Core/Expressions/Elementary/EmptyExpression.cs
| 2.890625
| 3
|
namespace YAMP
{
using System;
using System.Collections.Generic;
/// <summary>
/// The empty expression - just a dummy!
/// </summary>
sealed class EmptyExpression : Expression
{
#region ctor
public EmptyExpression()
{
}
#endregion
#region Methods
public override Value Interpret(IDictionary<String, Value> symbols)
{
return null;
}
public override void RegisterElement(IElementMapping elementMapping)
{
//Nothing here.
}
public override Expression Scan(ParseEngine engine)
{
return new EmptyExpression();
}
public override String ToCode()
{
return String.Empty;
}
#endregion
}
}
|
8fe82c047cc84e714ec267a0f163b70e5ece3f26
|
C#
|
VinceJH/HangManGame
|
/HangManGame/Form1.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.Threading.Tasks;
using System.Windows.Forms;
namespace HangManGame
{
public partial class Form1 : Form
{
public string[] wordsList;
string word2Guess = "";
int lengthOfGuessWord = 0;
int numberOfLives = 6;
Pen myPen = new Pen(Color.Black);
Pen redPen = new Pen(Color.Red);
string multiplayerWord2Guess = " ";
public Form1()
{
InitializeComponent();
MessageBox.Show("Welcome to Hangman!\nPlease Enter the Amount of Players You Would Like to Play with below.\nHave Fun!", "Hangman Game");
btGuess.Enabled = false;
btRestart.Enabled = false;
txbLettersGuessed.Enabled = false;
txbPhrase.Enabled = false;
txbLetterEntered.Enabled = false;
}
private void button1_Click(object sender, EventArgs e) { }
private void btRestart_Click(object sender, EventArgs e)
{
numberOfLives = 6;
if (MessageBox.Show("Are you sure you want to proceed?\nAll Your Progress Will be lost!", "HangMan Game Change Phrase?", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
{
txbLettersGuessed.Clear();
txbLetterEntered.Clear();
txbPhrase.Clear();
pnHangmanBox.Refresh();
int randomNumber = 0;
txbPhrase.Text = "";
Random wordsListgenerator = new Random();
wordsList = new string[10] { "hangman", "csharpgame", "treetop", "minecraft", "television", "computer", "keyboard", "mouse", "jeb", "vince" };
randomNumber = wordsListgenerator.Next(0, 9);
word2Guess = wordsList[randomNumber];
MessageBox.Show("Your new random word has been created!\nStart Guessing on the Right. =>", "Hangman Game New Word");
lengthOfGuessWord = word2Guess.Length;
for (int i = 0; i < lengthOfGuessWord; i++)
{
txbPhrase.Text = txbPhrase.Text + "?";
}
}
}
private void btSinglePlayer_Click(object sender, EventArgs e)
{
numberOfLives = 6;
int randomNumber = 0;
txbPhrase.Text = "";
Random wordsListgenerator = new Random();
wordsList = new string[10] { "hangman", "csharpgame", "treetop", "minecraft", "television", "computer", "keyboard", "mouse", "jeb", "vince" };
randomNumber = wordsListgenerator.Next(0, 9);
word2Guess = wordsList[randomNumber];
MessageBox.Show("Your random word has been created!\nStart Guessing on the Right. =>", "Hangman Game Start");
lengthOfGuessWord = word2Guess.Length;
for(int i = 0; i < lengthOfGuessWord; i++)
{
txbPhrase.Text = txbPhrase.Text + "?";
}
btSinglePlayer.Enabled = false;
btMultiPlayer.Enabled = false;
btGuess.Enabled = true;
btRestart.Enabled = true;
txbLetterEntered.Enabled = true;
}
private void pnHangmanBox_Paint(object sender, PaintEventArgs e)
{
Graphics hanger = e.Graphics;
myPen.Width = 3;
hanger.DrawLine(myPen, 76, 15, 76, 40);
hanger.DrawLine(myPen, 76, 15, 260, 15);
hanger.DrawLine(myPen, 260, 15, 260, 260);
hanger.DrawLine(myPen, 200, 260, 320, 260);
if(numberOfLives < 6)
{//Head
Graphics g = e.Graphics;
myPen.Width = 4;
g.DrawEllipse(myPen, 40, 40, 76, 76);
}
if (numberOfLives < 5)
{//body
int x1 = 78;
int y1 = 116;
int x2 = 78;
int y2 = 196;
Graphics l = e.Graphics;
myPen.Width = 5;
l.DrawLine(myPen, x1, y1, x2, y2);
}
if(numberOfLives < 4)
{//arm left
Graphics j = e.Graphics;
myPen.Width = 5;
j.DrawLine(myPen, 78, 131, 28, 176);
}
if (numberOfLives < 3)
{//arm right
Graphics i = e.Graphics;
myPen.Width = 5;
i.DrawLine(myPen, 78, 131, 128, 176);
}
if (numberOfLives < 2)
{//leg left
Graphics k = e.Graphics;
myPen.Width = 5;
k.DrawLine(myPen, 78, 196, 43, 241);
}
if (numberOfLives < 1)
{//leg right
Graphics q = e.Graphics;
myPen.Width = 5;
q.DrawLine(myPen, 78, 196, 113, 241);
redPen.Width = 15;
q.DrawLine(redPen, 30, 50, 135, 230);
q.DrawLine(redPen, 135, 50, 30, 230);
}
}
private void txbLetterEntered_TextChanged(object sender, EventArgs e) { }
private void btGuess_Click(object sender, EventArgs e)
{
string phrase = txbPhrase.Text;
char letterpicked = ' ';
string s = " ";
string t = " ";
s = txbLetterEntered.Text;
t = txbLetterEntered.Text;
try
{
letterpicked = char.Parse(s);
}
catch (FormatException)
{
MessageBox.Show("Invaild Input " + s, "Check");
txbLetterEntered.Clear();
return;
}
if (char.IsUpper(letterpicked))
{
MessageBox.Show("UpperCase Letters will not be accepted.\nPlease try the letter in a LowerCase form.\nSorry For the Inconvience.", "Hangman Game Check");
return;
}
txbLettersGuessed.Text = txbLettersGuessed.Text + t + ", ";
txbLetterEntered.Text = "";
string str = txbPhrase.Text;
string isCorrect = txbPhrase.Text;
for (int i = 0; i < word2Guess.Length; i++)
{
if (word2Guess[i] == letterpicked)
{
char phraseFixer = txbPhrase.Text[i];
int pos = i;
char replacement = letterpicked;
StringBuilder sb = new StringBuilder(str);
sb[pos] = replacement;
str = sb.ToString();
txbPhrase.Text = str;
}
}
if (word2Guess == txbPhrase.Text)
{
MessageBox.Show("Congradulations!!!\nYou Have Won!!!\nClick Play Again to Start A New Game", "HangMan Game Win");
btRestart.Enabled = false;
btGuess.Enabled = false;
}
if(txbPhrase.Text == isCorrect)
{
numberOfLives = numberOfLives - 1;
MessageBox.Show("Whoops! That was Incorrect.\nKeep guessing before you get hung", "Hangman Wrong Guess");
pnHangmanBox.Invalidate();
}
if(numberOfLives == 0)
{
MessageBox.Show(String.Format("Oh No! You got hung!\nGame Over.\nClick Below to Play Again"), "Hangman Game Lost");
MessageBox.Show(word2Guess, "Correct Phrase");
btGuess.Enabled = false;
btRestart.Enabled = false;
}
}
private void btPlayAgain_Click(object sender, EventArgs e)
{
numberOfLives = 6;
if (MessageBox.Show("Are you sure you want to proceed?\nAll Your Existing Progress Will be lost!", "HangMan Game New Game?", MessageBoxButtons.YesNoCancel) == DialogResult.Yes)
{
txbLettersGuessed.Clear();
txbLetterEntered.Clear();
txbPhrase.Clear();
pnHangmanBox.Refresh();
MessageBox.Show("Welcome to Hangman!\nPlease Enter the Amount of Players You Would Like to Play with below.", "Hangman Game New Game");
btSinglePlayer.Enabled = true;
btMultiPlayer.Enabled = true;
btGuess.Enabled = false;
btRestart.Enabled = false;
txbLetterEntered.Enabled = false;
}
}
private void btExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btMultiPlayer_Click(object sender, EventArgs e)
{
numberOfLives = 6;
HangManMultiPlayer form2 = new HangManMultiPlayer();
form2.ShowDialog();
multiplayerWord2Guess = form2.phraseEntered;
btSinglePlayer.Enabled = false;
btMultiPlayer.Enabled = false;
btGuess.Enabled = true;
txbLetterEntered.Enabled = true;
for (int i = 0; i < multiplayerWord2Guess.Length; i++)
{
txbPhrase.Text = txbPhrase.Text + "?";
}
word2Guess = multiplayerWord2Guess;
}
private void label5_Click(object sender, EventArgs e) { }
}
}
|
f451dadf43d5c272e0170b3d10403b989f495ed7
|
C#
|
Mushu1988/smallProjects
|
/C#/Calculator/Calculator/MainWindow.xaml.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Calculator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
bool isFirst=true;
Button operation;
double value1;
double value2;
double result;
public MainWindow()
{
InitializeComponent();
tb1stValue.Focus();
}
private void NumberButton_Click(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
string value = button.Content.ToString();
if (isFirst)
{
tb1stValue.AppendText(value);
tb1stValue.Focus();
tb1stValue.CaretIndex = tb1stValue.Text.Length;
}
else
{
tb2ndValue.AppendText(value);
tb2ndValue.Focus();
tb2ndValue.CaretIndex = tb2ndValue.Text.Length;
}
}
private void PlusMinus_ButtonClick(object sender, RoutedEventArgs e)
{
if (isFirst)
{
if (tb1stValue.Text.Substring(0, 1) == "-")
{
tb1stValue.Text = tb1stValue.Text.Replace("-", "");
}
else tb1stValue.Text = "-" + tb1stValue.Text;
tb1stValue.Focus();
tb1stValue.CaretIndex = tb1stValue.Text.Length;
}
else
{
if (tb2ndValue.Text.Substring(0, 1) == "-")
{
tb2ndValue.Text = tb2ndValue.Text.Replace("-", "");
}
else tb2ndValue.Text = "-" + tb2ndValue.Text;
tb2ndValue.Focus();
tb2ndValue.CaretIndex = tb2ndValue.Text.Length;
}
}
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("^[-]?[0-9]*[\\.]?[0-9]*$");
if (isFirst)
{
tb1stValue.Background = regex.IsMatch(e.Text) ? Brushes.LightGreen : Brushes.LightSalmon;
}
else tb2ndValue.Background = regex.IsMatch(e.Text) ? Brushes.LightGreen : Brushes.LightSalmon;
e.Handled = (!regex.IsMatch(e.Text));
}
private void ClearAll_ButtonClick(object sender, RoutedEventArgs e)
{
tb1stValue.Text = "";
tb2ndValue.Text = "";
tb2ndValue.IsEnabled = false;
lblOperation.Content = "";
tbResult.Text = "";
tbResult.IsEnabled = false;
tb1stValue.IsEnabled = true;
tb1stValue.Focus();
btEquals.IsEnabled = false;
isFirst = true;
}
private void Operations_ButtonClick(object sender, RoutedEventArgs e)
{
operation = sender as Button;
if (!double.TryParse(tb1stValue.Text, out value1))
{
MessageBox.Show("Invalid number in 1st value field", "MyCalculator", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
tb1stValue.IsEnabled = false;
tb2ndValue.IsEnabled = true;
tb2ndValue.Focus();
tb2ndValue.Background = Brushes.LightGreen;
lblOperation.Content = operation.Content;
isFirst = false;
}
private void Tb1stValue_TextChanged(object sender, TextChangedEventArgs e)
{
if (tb1stValue.Text.Length >= 1)
{
btAddition.IsEnabled = true;
btDivide.IsEnabled = true;
btExtraction.IsEnabled = true;
btMultiply.IsEnabled = true;
}
}
private void Equals_ButtonClick(object sender, RoutedEventArgs e)
{
if (!double.TryParse(tb2ndValue.Text, out value2))
{
MessageBox.Show("Invalid number in 1st value field", "MyCalculator", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
tb2ndValue.Background = Brushes.LightGreen;
tb2ndValue.IsEnabled = false;
switch (operation.Name)
{
case "btAddition":
result = value1 + value2;
break;
case "btExtraction":
result = value1 - value2;
break;
case "btMultiply":
result = value1 * value2;
break;
case "btDivide":
if (value2 != 0)
{
result = value1 / value2;
break;
}
else
{
tb2ndValue.Background = Brushes.LightSalmon;
MessageBox.Show("Can not divide by 0!", "MyCalculator", MessageBoxButton.OK, MessageBoxImage.Error);
tb2ndValue.IsEnabled = true;
return;
}
default:
MessageBox.Show("Can not precoess the operation!", "MyCalculator", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
tbResult.Focus();
tbResult.Background = Brushes.LightGreen;
tbResult.Text = result.ToString();
}
private void Tb2ndValue_TextChanged(object sender, TextChangedEventArgs e)
{
if (tb2ndValue.Text.Length >= 1)
{
btEquals.IsEnabled = true;
tbResult.IsEnabled = true;
btAddition.IsEnabled = false;
btDivide.IsEnabled = false;
btExtraction.IsEnabled = false;
btMultiply.IsEnabled = false;
}
}
}
}
|
8e6973a876d1e83adc52a6d56e46f2a3f037e96b
|
C#
|
icnocop/cuite
|
/src/CUITe/Controls/HtmlControls/HtmlTable.cs
| 2.71875
| 3
|
using CUITe.SearchConfigurations;
using mshtml;
using Microsoft.VisualStudio.TestTools.UITesting;
using CUITControls = Microsoft.VisualStudio.TestTools.UITesting.HtmlControls;
namespace CUITe.Controls.HtmlControls
{
/// <summary>
/// Represents a table control for Web page user interface (UI) testing.
/// </summary>
public class HtmlTable : HtmlControl<CUITControls.HtmlTable>
{
/// <summary>
/// Initializes a new instance of the <see cref="HtmlTable"/> class.
/// </summary>
/// <param name="searchConfiguration">The search configuration.</param>
public HtmlTable(By searchConfiguration = null)
: this(new CUITControls.HtmlTable(), searchConfiguration)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="HtmlTable"/> class.
/// </summary>
/// <param name="sourceControl">The source control.</param>
/// <param name="searchConfiguration">The search configuration.</param>
public HtmlTable(CUITControls.HtmlTable sourceControl, By searchConfiguration = null)
: base(sourceControl, searchConfiguration)
{
}
/// <summary>
/// Gets the number of columns in this table.
/// </summary>
public int ColumnCount
{
get
{
WaitForControlReadyIfNecessary();
return SourceControl.ColumnCount;
}
}
/// <summary>
/// Gets the number of rows in this table.
/// </summary>
public int RowCount
{
get
{
WaitForControlReadyIfNecessary();
return SourceControl.Rows.Count;
}
}
/// <summary>
/// Finds a row by using specified <paramref name="valueToSearch"/> and clicks its column
/// specified by <paramref name="columnIndex"/>.
/// </summary>
/// <param name="valueToSearch">The value to search.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <param name="searchOptions">The search options.</param>
public void FindRowAndClick(
string valueToSearch,
int columnIndex,
HtmlTableSearchOptions searchOptions = HtmlTableSearchOptions.Normal)
{
int rowIndex = FindRowIndex(valueToSearch, columnIndex, searchOptions);
FindCellAndClick(rowIndex, columnIndex);
}
/// <summary>
/// Finds a row by using specified <paramref name="valueToSearch"/> and double-clicks its
/// column specified by <paramref name="columnIndex"/>.
/// </summary>
/// <param name="valueToSearch">The value to search.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <param name="searchOptions">The search options.</param>
public void FindRowAndDoubleClick(
string valueToSearch,
int columnIndex,
HtmlTableSearchOptions searchOptions = HtmlTableSearchOptions.Normal)
{
int rowIndex = FindRowIndex(valueToSearch, columnIndex, searchOptions);
FindCellAndDoubleClick(rowIndex, columnIndex);
}
/// <summary>
/// Finds the header cell by specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/> and clicks it.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
public void FindHeaderCellAndClick(int rowIndex, int columnIndex)
{
GetHeaderCell(rowIndex, columnIndex).Click();
}
/// <summary>
/// Finds the cell by specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/> and clicks it.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
public void FindCellAndClick(int rowIndex, int columnIndex)
{
GetCell<HtmlControl<CUITControls.HtmlControl>>(rowIndex, columnIndex).Click();
}
/// <summary>
/// Finds the cell by specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/> and double-clicks it.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
public void FindCellAndDoubleClick(int rowIndex, int columnIndex)
{
GetCell(rowIndex, columnIndex).DoubleClick();
}
/// <summary>
/// Finds a row index by using specified <paramref name="valueToSearch"/> and
/// <paramref name="columnIndex"/>.
/// </summary>
/// <param name="valueToSearch">The value to search.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <param name="searchOptions">The search options.</param>
public int FindRowIndex(
string valueToSearch,
int columnIndex,
HtmlTableSearchOptions searchOptions)
{
WaitForControlReadyIfNecessary();
int iRow = -1;
int rowCount = -1;
foreach (CUITControls.HtmlControl control in SourceControl.Rows)
{
//control could be of ControlType.RowHeader or ControlType.Row
rowCount++;
int columnCount = -1;
foreach (CUITControls.HtmlControl cell in control.GetChildren()) //Cells could be a collection of HtmlCell and HtmlHeaderCell controls
{
columnCount++;
bool searchOptionResult = false;
if (columnCount == columnIndex)
{
if (searchOptions == HtmlTableSearchOptions.Normal)
{
searchOptionResult = (valueToSearch == cell.InnerText);
}
else if (searchOptions == HtmlTableSearchOptions.NormalTight)
{
searchOptionResult = (valueToSearch == cell.InnerText.Trim());
}
else if (searchOptions == HtmlTableSearchOptions.StartsWith)
{
searchOptionResult = cell.InnerText.StartsWith(valueToSearch);
}
else if (searchOptions == HtmlTableSearchOptions.EndsWith)
{
searchOptionResult = cell.InnerText.EndsWith(valueToSearch);
}
else if (searchOptions == HtmlTableSearchOptions.Greedy)
{
searchOptionResult = (cell.InnerText.IndexOf(valueToSearch) > -1);
}
if (searchOptionResult)
{
iRow = rowCount;
break;
}
}
}
if (iRow > -1)
break;
}
return iRow;
}
/// <summary>
/// Gets the value of the cell with specified row and column index.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <returns>The value of the cell with specified row and column index.</returns>
public string GetCellValue(int rowIndex, int columnIndex)
{
return GetCellValue<HtmlCell>(rowIndex, columnIndex);
}
/// <summary>
/// Gets the value of the header cell with specified row and column index.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <returns>The value of the cell with specified row and column index.</returns>
public string GetHeaderCellValue(int rowIndex, int columnIndex)
{
return GetCellValue<HtmlHeaderCell>(rowIndex, columnIndex);
}
/// <summary>
/// Gets the embedded check box at specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/>.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
/// <returns></returns>
public HtmlCheckBox GetEmbeddedCheckBox(int rowIndex, int columnIndex)
{
string sSearchProperties = "";
var td = (IHTMLElement)GetCell(rowIndex, columnIndex).SourceControl.NativeElement;
IHTMLElement check = GetEmbeddedCheckBoxNativeElement(td);
string outerHtml = check.outerHTML.Replace("<", "").Replace(">", "").Trim();
string[] saTemp = outerHtml.Split(' ');
var chk = new CUITControls.HtmlCheckBox(SourceControl.Container);
foreach (string sTemp in saTemp)
{
if (sTemp.IndexOf('=') > 0)
{
string[] saKeyValue = sTemp.Split('=');
string sValue = saKeyValue[1];
if (saKeyValue[0].ToLower() == "name")
{
sSearchProperties += ";Name=" + sValue;
chk.SearchProperties.Add(UITestControl.PropertyNames.Name, sValue);
}
if (saKeyValue[0].ToLower() == "id")
{
sSearchProperties += ";Id=" + sValue;
chk.SearchProperties.Add(CUITControls.HtmlControl.PropertyNames.Id, sValue);
}
if (saKeyValue[0].ToLower() == "class")
{
sSearchProperties += ";Class=" + sValue;
chk.SearchProperties.Add(CUITControls.HtmlControl.PropertyNames.Class, sValue);
}
}
}
if (sSearchProperties.Length > 1)
{
sSearchProperties = sSearchProperties.Substring(1);
}
return new HtmlCheckBox(chk, By.SearchProperties(sSearchProperties));
}
/// <summary>
/// Gets the column headers of the html table.
/// </summary>
public string[] GetColumnHeaders()
{
UITestControlCollection rows = SourceControl.Rows;
if ((rows != null) && (rows.Count > 0))
{
if ((rows[0] != null) && (rows[0].ControlType == ControlType.RowHeader))
{
var headers = rows[0].GetChildren();
var columnHeaders = new string[headers.Count];
for (int i = 0; i < columnHeaders.Length; i++)
{
columnHeaders[i] = (string)headers[i].GetProperty("Value");
}
return columnHeaders;
}
}
return null;
}
/// <summary>
/// Gets the header cell at specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/>.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
public HtmlHeaderCell GetHeaderCell(int rowIndex, int columnIndex)
{
return GetCell<HtmlHeaderCell>(rowIndex, columnIndex);
}
/// <summary>
/// Gets the cell at specified <paramref name="rowIndex"/> and
/// <paramref name="columnIndex"/>.
/// </summary>
/// <param name="rowIndex">Index of the row.</param>
/// <param name="columnIndex">Index of the column.</param>
public HtmlCell GetCell(int rowIndex, int columnIndex)
{
return GetCell<HtmlCell>(rowIndex, columnIndex);
}
private string GetCellValue<T>(int iRow, int iCol) where T : ControlBase, IHasInnerText
{
string innerText = "";
T htmlCell = GetCell<T>(iRow, iCol);
if (htmlCell != null)
{
innerText = htmlCell.InnerText;
}
return innerText;
}
private T GetCell<T>(int iRow, int iCol) where T : ControlBase, IHasInnerText
{
WaitForControlReadyIfNecessary();
UITestControl htmlCell = null;
int rowCount = -1;
foreach (UITestControl row in SourceControl.Rows)
{
//control could be of ControlType.RowHeader or ControlType.Row
rowCount++;
if (rowCount != iRow)
{
continue;
}
int colCount = -1;
foreach (UITestControl cell in row.GetChildren()) //Cells could be a collection of HtmlCell and HtmlHeaderCell controls
{
colCount++;
if (colCount != iCol)
{
continue;
}
htmlCell = cell;
break;
}
if (htmlCell != null)
{
break;
}
}
return ControlBaseFactory.Create<T>(htmlCell, null);
}
private static IHTMLElement GetEmbeddedCheckBoxNativeElement(IHTMLElement parent)
{
while (true)
{
foreach (IHTMLElement ele2 in parent.children)
{
if (ele2.tagName.ToUpper() == "INPUT")
{
string sType = ele2.getAttribute("type");
if (sType.ToLower() == "checkbox")
{
return ele2;
}
}
else
{
if (ele2.children != null)
{
parent = ele2;
}
}
}
}
}
}
}
|
d5314d47cb0758143e8244700d9afc1d9f8366a6
|
C#
|
alephist/edabit-coding-challenges
|
/CSharp/ShowLettersOnly.cs
| 3.703125
| 4
|
using System.Linq;
namespace CSharp
{
// Write a function that removes any non-letters from a string, returning a well-known film title.
// https://edabit.com/challenge/moqcQ563NukBBbKDL
public static class ShowLettersOnly
{
public static string LettersOnly(string str)
{
var letters = str.ToCharArray().Where(char.IsLetter).ToArray();
return new string(letters);
}
}
}
|
574590ae23b4491a6cff759c099408714ce0cf76
|
C#
|
fccoul/QC-2018
|
/PREM/save/PREM/PL_Prem/PL_Prem_iut/Attributs/AjaxRequestAttribute.cs
| 2.6875
| 3
|
using System.Web.Mvc;
namespace RAMQ.PRE.PL_Prem_iut.Attributs
{
/// <summary>
/// Permet de limiter l'accès a une action seulement si elle est appelé depuis une requête Ajax
/// </summary>
/// <remarks>
/// Auteur : Kévin Follier <br/>
/// Date : 2015-09-16
/// </remarks>
public class AjaxRequestAttribute : ActionMethodSelectorAttribute
{
#region Méthodes publiques
/// <summary>
/// Permet de savoir si l'action concernée est valide pour la requête courante
/// </summary>
/// <param name="controllerContext"></param>
/// <param name="methodInfo"></param>
/// <returns></returns>
/// <remarks></remarks>
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
#endregion
}
}
|
9be5269e901db8a71a6d71b83d0659fa57440bf3
|
C#
|
nilson-coder/Aula7_manipulacao
|
/EX/Program.cs
| 2.765625
| 3
|
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace EX
{
class Program
{
static void Main(string[] args)
{
#region Documento
Document exemploDoc = new Document();
#endregion
#region seção no Documento
Section secaocapa = exemploDoc.AddSection();
#endregion
#region Criar um paragrafo
Paragraph titulo = secaocapa.AddParagraph();
#endregion
#region Adiciona texto ao paragrafo
titulo.AppendText("Exercícios resulvido\n\n");
#endregion
#region texto
titulo.Format.HorizontalAlignment = HorizontalAlignment.Center;
#endregion
#region
#endregion
#region Salvar arquivo
exemploDoc.SaveToFile(@"saida\exemplo_arquivo_word.docx", FileFormat.Docx);
#endregion
}
}
}
|
f14164cb4c1e5bc7fc08377d462712e7c5bf0a73
|
C#
|
TonyMajorDev/DeChargerRepo
|
/Science/MassSpectrometry/Extensions.cs
| 3.03125
| 3
|
//-----------------------------------------------------------------------
// Copyright 2018 Eli Lilly and Company
//
// Licensed under the Apache License, Version 2.0 (the "License");
//
// you may not use this file except in compliance with the License.
//
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//-----------------------------------------------------------------------
using SignalProcessing;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
public static partial class Extensions
{
public static void TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> lookup, TKey key, TValue value)
{
if (!lookup.ContainsKey(key)) lookup.Add(key, value);
}
//public static void TrySum<TKey, TValue>(this IDictionary<TKey, TValue> lookup, TKey key, TValue value)
//{
// if (!lookup.ContainsKey(key))
// lookup.Add(key, value);
// else
// lookup[key] += (double?)value;
//}
public static void TrySum(this PointSet lookup, double key, float value)
{
if (!lookup.ContainsKey(key))
lookup.Add(key, value);
else
lookup[key] += value;
}
/// <summary>
/// This is just like the regular Add method, except it checks for null before adding, and if the value is null, the item is simply not added.
/// So the null value is skipped, hence the name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="aList"></param>
/// <param name="theValue">Object to be added</param>
public static void AddSkipNull<T>(this System.Collections.Generic.List<T> aList, T theValue)
{
if (theValue != null) aList.Add(theValue);
}
public static double Median(this IEnumerable<double> source)
{
if (source.Count() == 0)
{
throw new InvalidOperationException("Cannot compute median for an empty set.");
}
var sortedList = from number in source
orderby number
select number;
int itemIndex = (int)sortedList.Count() / 2;
if (sortedList.Count() % 2 == 0)
{
// Even number of items.
return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2;
}
else
{
// Odd number of items.
return sortedList.ElementAt(itemIndex);
}
}
static SortedList<string, IEnumerable<string>> cache = new SortedList<string, IEnumerable<string>>();
public static IEnumerable<string> ToSymbols(this string sequence)
{
if (cache.ContainsKey(sequence)) return cache[sequence];
if (cache.Count > 100) cache.Clear(); // crude cache size limiting
var result = new List<string>();
for (int i = 0; i < sequence.Length; i++)
{
if (string.IsNullOrWhiteSpace(sequence[i].ToString()) == false)
{
if (i + 1 < sequence.Length && string.IsNullOrWhiteSpace(sequence[i + 1].ToString()) == false && sequence[i + 1].ToString().ToLower() == sequence[i].ToString())
{
result.Add(new string(new char[] { sequence[i], sequence[i + 1] })); // two letter symbol
i++;
continue;
}
result.Add(sequence[i].ToString()); // single letter symbol
}
}
cache.Add(sequence, result);
return result;
}
//public static double Median(this IEnumerable<double> source)
//{
// var sortedList = from number in source
// orderby number
// select number;
// int count = sortedList.Count();
// int itemIndex = count / 2;
// if (count % 2 == 0) // Even number of items.
// return (sortedList.ElementAt(itemIndex) +
// sortedList.ElementAt(itemIndex - 1)) / 2;
// // Odd number of items.
// return sortedList.ElementAt(itemIndex);
//}
public static double? Median(this IEnumerable<double?> source)
{
var sortedList = from number in source.Where(x => x.HasValue).Select(v => v.Value)
orderby number
select number;
int count = sortedList.Count();
int itemIndex = count / 2;
if (count % 2 == 0) // Even number of items.
{
var avg = (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2;
// Return the item closest to the average
return (Math.Abs(sortedList.ElementAt(itemIndex) - avg) > Math.Abs(sortedList.ElementAt(itemIndex - 1) - avg)) ? sortedList.ElementAt(itemIndex - 1) : sortedList.ElementAt(itemIndex);
}
// Odd number of items.
return sortedList.ElementAt(itemIndex);
}
public static float Median(this IEnumerable<float> source)
{
var sortedList = from number in source
orderby number
select number;
int count = sortedList.Count();
int itemIndex = count / 2;
if (count % 2 == 0) // Even number of items.
{
var avg = (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2;
// Return the item closest to the average
return (Math.Abs(sortedList.ElementAt(itemIndex) - avg) > Math.Abs(sortedList.ElementAt(itemIndex - 1) - avg)) ? sortedList.ElementAt(itemIndex - 1) : sortedList.ElementAt(itemIndex);
}
// Odd number of items.
return sortedList.ElementAt(itemIndex);
}
public static double WeightedAverage<T>(this IEnumerable<T> records, Func<T, double> value, Func<T, double> weight)
{
// Based on http://stackoverflow.com/questions/2714639/weighted-average-with-linq
// usage: double weightedAverage = records.WeightedAverage(record => record.PCR, record => record.LENGTH);
double weightedValueSum = records.Sum(record => value(record) * weight(record));
double weightSum = records.Sum(record => weight(record));
if (weightSum != 0)
return weightedValueSum / weightSum;
else
throw new DivideByZeroException("Your message here");
}
/// <summary>
/// Return a SHA256 from a file
/// </summary>
/// <param name="aFile"></param>
/// <returns>hashcode as a string</returns>
public static string Sha256Hash(this FileInfo aFile)
{
using (var hash = SHA256.Create())
{
//return BitConverter.ToString(hash.ComputeHash(aFile.OpenRead())).Replace("-", "");
// open file as shared so that you avoid the "file in use" error if it is already open
return BitConverter.ToString(hash.ComputeHash(aFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))).Replace("-", "");
}
}
/// <summary>
/// Return a SHA256 from a Directory
/// </summary>
/// <param name="aDir"></param>
/// <returns>hashcode as a string</returns>
public static string Sha256Hash(this DirectoryInfo aDir)
{
// based on https://stackoverflow.com/questions/3625658/creating-hash-for-folder
var files = aDir.GetFiles("*", SearchOption.AllDirectories).OrderBy(p => p.Name).ToArray();
using (var sha256 = SHA256.Create())
{
foreach (var aFile in files)
{
// hash path
byte[] pathBytes = Encoding.UTF8.GetBytes(aFile.Name); // use relative path here?
sha256.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// hash contents
//byte[] contentBytes = File.ReadAllBytes(aFile.FullName);
//var s = aFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//byte[] contentBytes = new byte[aFile.Length];
//s.Read(contentBytes, 0, contentBytes.Length);
//sha256.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
// Based on: https://stackoverflow.com/questions/20634827/how-to-compute-hash-of-a-large-file-chunk
using (var fileStream = aFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
fileStream.Position = 0;
long bytesToHash = fileStream.Length;
var buf = new byte[128 * 1024]; // chunk buffer
while (bytesToHash > 0)
{
var bytesRead = fileStream.Read(buf, 0, (int)Math.Min(bytesToHash, buf.Length));
sha256.TransformBlock(buf, 0, bytesRead, null, 0);
bytesToHash -= bytesRead;
if (bytesRead == 0)
throw new InvalidOperationException("Unexpected end of stream");
}
};
}
//Handles empty filePaths case
sha256.TransformFinalBlock(new byte[0], 0, 0);
return BitConverter.ToString(sha256.Hash).Replace("-", "");
}
}
///// <summary>
///// Return a SHA256 from a Directory
///// </summary>
///// <param name="aDir"></param>
///// <returns>hashcode as a string</returns>
//public static string Sha256Hash2(this DirectoryInfo aDir)
//{
// // based on https://stackoverflow.com/questions/3625658/creating-hash-for-folder
// // This method uses streams to minimize memory usage.
// var files = aDir.GetFiles("*", SearchOption.AllDirectories).OrderBy(p => p).ToArray();
// using (var sha256 = SHA256.Create())
// {
// foreach (var aFile in files)
// {
// var fileStream = aFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// // Based on: https://blogs.msdn.microsoft.com/shawnfa/2004/02/20/using-the-hashing-transforms-or-how-do-i-compute-a-hash-block-by-block/
// // and: https://stackoverflow.com/questions/2124468/possible-to-calculate-md5-or-other-hash-with-buffered-reads
// using (var cs = new CryptoStream(fileStream, sha256, CryptoStreamMode.Read))
// {
// cs.
// // hash path
// var filenameAsBytes = Encoding.UTF8.GetBytes(aFile.Name); // use relative path here?
// cs.Write(filenameAsBytes, 0, filenameAsBytes.Length);
// while (notDoneYet)
// {
// buffer = Get32MB();
// cs.Write(buffer, 0, buffer.Length);
// fileStream
// }
// System.Console.WriteLine(BitConverter.ToString(sha256.Hash));
// }
// // hash path
// //byte[] pathBytes = Encoding.UTF8.GetBytes(aFile.Name); // use relative path here?
// //sha256.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// // hash contents
// byte[] contentBytes = File.ReadAllBytes(aFile.FullName);
// //aFile.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
// //sha256.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
// fileStream.Close();
// }
// //TODO: test the empty folder case
// //Handles empty filePaths case
// //sha256.TransformFinalBlock(new byte[0], 0, 0);
// return BitConverter.ToString(sha256.Hash).Replace("-", "");
// }
//}
public static string Sha256Hash(this FileSystemInfo aFileOrDir)
{
if (aFileOrDir is FileInfo) return (aFileOrDir as FileInfo).Sha256Hash();
return (aFileOrDir as DirectoryInfo).Sha256Hash();
}
}
|
90ad83a1c2274e70a41db0a862be65dd2c223de8
|
C#
|
Drockio/livemusicfriend
|
/LiveMusicFriend/Helpers/Utility.cs
| 3.109375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LiveMusicFriend.Helpers
{
public static class Utility
{
public static DateTime? GetDate(string DateString)
{
DateTime dt;
if (DateTime.TryParse(DateString, out dt))
return dt;
else
return null;
}
public static int? GetInt(string IntString)
{
int outInt;
if (Int32.TryParse(IntString, out outInt))
return outInt;
else
return null;
}
public static Uri GetUri(String uri)
{
if (Uri.IsWellFormedUriString(uri, UriKind.Absolute))
return new Uri(uri);
else
return null;
}
}
}
|
4ce20980ebad4191abe24ad67c912c2618b6f0b7
|
C#
|
nickh671/IT-507-OOP
|
/Week5/Hertozg_6_5/Form1.cs
| 3.03125
| 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 Hertozg_6_5
{
public partial class Form1 : Form
{
//hourly rate for labor
private double hourlyRate = 20.00;
//var for sales tax percent
private double salesTax = .06;
//dictionary to hold the values of the prices for each possible repair
//couldve just made separable variables for each price but I prefer the dictionary. Makes it cleaner and easier to adapt later in my opinion
private Dictionary<string, double> prices = new Dictionary<string, double>() {
{"Oil Change", 26.00 },
{"Lube Job", 18.00 },
{"Radiator Flush", 30.00 },
{"Transmission Flush", 80.00 },
{"Inspection", 15.00 },
{"Muffler Replacement", 100.00 },
{"Tire Rotation", 20.00 }
};
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//onclick function for exit button, calls the close function
private void exitButton_Click(object sender, EventArgs e)
{
Close();
}
//function to calculate charges from the oil and lube group checkboxes
//if checked, the dictionary is checked with the key corresponding to the service
//if price is found, price is added to a running total and then returned
private double OilLubeCharges()
{
double total = 0;
if (oilCheckBox.Checked)
{
total += prices["Oil Change"];
}
if (lubeCheckBox.Checked)
{
total += prices["Lube Job"];
}
return total;
}
//function to calculate charges from the flushes group checkboxes
//if checked, the dictionary is checked with the key corresponding to the service
//if price is found, price is added to a running total and then returned
private double FlushCharges()
{
double total = 0;
if (radFlushCheckBox.Checked)
{
total += prices["Radiator Flush"];
}
if (transFlushCheckBox.Checked)
{
total += prices["Transmission Flush"];
}
return total;
}
//function to calculate charges from the misc group checkboxes
//if checked, the dictionary is checked with the key corresponding to the service
//if price is found, price is added to a running total and then returned
private double MiscCharges()
{
double total = 0;
if (inspectionCheckBox.Checked)
{
total += prices["Inspection"];
}
if (mufflerCheckBox.Checked)
{
total += prices["Muffler Replacement"];
}
if (tireRotationCheckBox.Checked)
{
total += prices["Tire Rotation"];
}
return total;
}
//function to calculate charges from the other group checkboxes
//if checked, the dictionary is checked with the key corresponding to the service
//if price is found, price is added to a running total and then returned
private double OtherCharges()
{
double total = 0;
//checking to make sure that the user entered something and if they did, it is a parsable value
if (!string.IsNullOrWhiteSpace(partsTextBox.Text) && double.TryParse(partsTextBox.Text, out _))
{
total += double.Parse(partsTextBox.Text);
}
if (!string.IsNullOrWhiteSpace(laborTextBox.Text) && double.TryParse(laborTextBox.Text, out _))
{
total += double.Parse(laborTextBox.Text);
}
return total;
}
//function to calculate charges from the summary group checkboxes
//if checked/populated, the dictionary is checked with the key corresponding to the service
//if price is found, price is added to a running total and then returned
private double TaxCharges()
{
double total = 0;
if (!string.IsNullOrWhiteSpace(partsTextBox.Text) && double.TryParse(partsTextBox.Text, out _))
{
total += (double.Parse(partsTextBox.Text) * salesTax);
}
return total;
}
//using all our functions we made to calculate charges, we get the total charges
private double TotalCharges()
{
double total = 0;
total += OilLubeCharges();
total += FlushCharges();
total += MiscCharges();
total += OtherCharges();
total += TaxCharges();
return total;
}
//function to clear the oil and lube group checkboxes
private void ClearOilLube()
{
oilCheckBox.Checked = false;
lubeCheckBox.Checked = false;
}
//function to clear the flushes group checkboxes
private void ClearFlushes()
{
transFlushCheckBox.Checked = false;
radFlushCheckBox.Checked = false;
}
//function to clear the misc group checkboxes
private void ClearMisc()
{
inspectionCheckBox.Checked = false;
tireRotationCheckBox.Checked = false;
mufflerCheckBox.Checked = false;
}
//function to clear the other group textboxes
private void ClearOther()
{
laborTextBox.Text = "";
partsTextBox.Text = "";
}
//function to clear the summary group textboxes
private void ClearFees()
{
serviceLaborTextBox.Text = "";
totalTextBox.Text = "";
partsTotalTextBox.Text = "";
taxTextBox.Text = "";
}
//onclick function for the clear button. this calls all the clear functions above
private void clearButton_Click(object sender, EventArgs e)
{
ClearOilLube();
ClearFlushes();
ClearMisc();
ClearOther();
ClearFees();
}
private void calcButton_Click(object sender, EventArgs e)
{
//this is calculating the cost of JUST the parts so we can subtract it from the services and labor total
double partsVal;
if (!string.IsNullOrWhiteSpace(partsTextBox.Text) && double.TryParse(partsTextBox.Text, out _))
{
partsVal = double.Parse(partsTextBox.Text);
}
else
{
partsVal = 0;
}
//using our functions to display the final outputs with a string format to round the doubles to 2 decimal places
serviceLaborTextBox.Text = String.Format("{0:0.##}", (OilLubeCharges() + FlushCharges() + MiscCharges() + OtherCharges()) - partsVal);
partsTotalTextBox.Text = String.Format("{0:0.##}",partsVal.ToString());
taxTextBox.Text = String.Format("{0:0.##}", TaxCharges());
totalTextBox.Text = String.Format("{0:0.##}", TotalCharges());
}
private void serviceLaborTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
|
d5f13a451c4cd3a011f664d3c55d9795a70cca07
|
C#
|
ZOHIRE/switche_statement_chalenge
|
/switche_statement_chalenge/Program.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace switche_statement_chalenge
{
class Program
{
static void Main(string[] args)
{
string mysmartphon = "samsung";
switch (mysmartphon)
{
case "nokia":
Console.WriteLine("\n\n\n\n\t mysmart phone is nokia");
break;
case "motorola":
Console.WriteLine("\n\n\n\n\t mysmart phone is motorola");
break;
case "semense":
Console.WriteLine("\n\n\n\n\t mysmart phone is semense");
break;
case "samsung":
Console.WriteLine("\n\n\n\n\t mysmart phone is samsung");
break;
default:
Console.WriteLine("\n\n\n\n\t no one");
break;
}
//exercice:ااا He say helloنلاحظ انه في هدا التمرين لم يقم الكمبيوتر بطباعة الجملة
//وهذا بسبب ان الحرف الاول صغيير من كلمة hello
//علي عكسنت تعريف المتغير فانه حرف كبيرHello
string whatHesay = "Heloo";
switch (whatHesay)
{
case "heloo":
Console.WriteLine("\n\n\n\n\t He say hello");
break;
case "bey":
Console.WriteLine("\n\n\n\n\t He say bey");
break;
case "wilcom":
Console.WriteLine("\n\n\n\n\t He say wilcom");
break;
default:
Console.WriteLine("\n\n\n\n\t no one");
break;
}
/* Ternary Condition الشرط الثلاثي في لغة السي شارب */
string myName = "Isslam", myResult1;
myResult1 = myName.Equals ("Isslam")? "\n\n\n\t yes is my name" : "no is not my name";
Console.WriteLine(" {0}",myResult1);
int myVar = 7;
string myResult2 = (myVar < 9) ? "\n\n\n\t yes my var lesse 9" : "yes my var biger";
Console.WriteLine(" {0}",myResult2);
Console.ReadKey();
}
}
}
|
d4dc232f3991ec493f8afa3d5ae6d8a3431c9ed7
|
C#
|
eviternity/Apps4KidsWebApp
|
/Apps4KidsWeb/Apps4KidsWeb.Persistence/Connection.cs
| 2.546875
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.EntityClient;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Apps4KidsWeb.Persistence
{
/// <summary>
/// The class connection
/// </summary>
public class Connection
{
/// <summary>
/// The connection string
/// </summary>
private static string connectionString = null;
/// <summary>
/// Gets the context.
/// </summary>
/// <returns></returns>
public static Apps4KidsEntities GetContext()
{
Apps4KidsEntities result;
if (connectionString != null)
{
return new Apps4KidsEntities(connectionString);
}
EntityConnectionStringBuilder ecsb = new EntityConnectionStringBuilder();
SqlConnectionStringBuilder sqlcsb = new SqlConnectionStringBuilder();
ecsb.Metadata = @"res://*/DataModel.csdl|
res://*/DataModel.ssdl|
res://*/DataModel.msl";
ecsb.Provider = "System.Data.SqlClient";
sqlcsb.InitialCatalog = "Apps4Kids";
sqlcsb.DataSource = "localhost";
sqlcsb.UserID = "sa";
sqlcsb.Password = "123user!";
ecsb.ProviderConnectionString = sqlcsb.ToString();
result = new Apps4KidsEntities(ecsb.ConnectionString);
return result;
}
}
}
|
0bfca7df4d58c3e3a2f2231812a0a29750a12350
|
C#
|
terencetcf/Tt.App.Development.Starter
|
/tests/Tt.App.UnitTests/Services/ProductServiceTests.cs
| 2.5625
| 3
|
using FluentAssertions;
using Moq;
using NUnit.Framework;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Tt.App.Data;
using Tt.App.Data.Repositories;
using Tt.App.Services;
namespace Tt.App.UnitTests.Services
{
public class ProductServiceTests
{
private IProductService sut;
private const string ProductId = "1";
private Mock<IProductRepository> mockProductRepository;
[SetUp]
public void SetUp()
{
mockProductRepository = new Mock<IProductRepository>();
sut = new ProductService(mockProductRepository.Object);
}
[Test]
public async Task GetProductsAsync_Always_ReturnExpectedResult()
{
var response = new Collection<Product>
{
GetMockProduct()
};
mockProductRepository.Setup(s => s.GetProductsAsync()).ReturnsAsync(response);
var result = await sut.GetProductsAsync();
result.Should().BeEquivalentTo(response);
mockProductRepository.Verify(s => s.GetProductsAsync(), Times.Once);
}
[Test]
public async Task GetProductAsync_Always_ReturnExpectedResult()
{
var id = "";
var response = GetMockProduct();
mockProductRepository
.Setup(s => s.GetProductAsync(It.IsAny<string>()))
.ReturnsAsync(response)
.Callback<string>(param => id = param);
var result = await sut.GetProductAsync(ProductId);
result.Should().BeEquivalentTo(response);
id.Should().Be("1");
mockProductRepository.Verify(s => s.GetProductAsync(It.IsAny<string>()), Times.Once);
}
private static Product GetMockProduct()
{
return new Product { Id = ProductId, Name = "P1" };
}
}
}
|
c449b5d30c3778853e8c11af43c1b9a5a5901637
|
C#
|
geniuszxy/Counter
|
/Counter/Library/Counter4.cs
| 3.015625
| 3
|
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace Counter
{
sealed class Counter4 : Counter
{
private volatile int _v;
public override int Size
{
get { return 4; }
}
unsafe public override bool GetNextNumbers(byte[] output, int count, int offset)
{
int v0, v1;
uint max = uint.MaxValue - (uint)count;
do
{
v0 = _v;
if (unchecked((uint)v0 > max))
return false;
v1 = v0 + count;
}
while (v0 != Interlocked.CompareExchange(ref _v, v1, v0));
Marshal.Copy(new IntPtr(&v0), output, offset, 4);
return true;
}
unsafe public override void PeekNextNumber(byte[] output, int offset)
{
fixed(int* p = &_v)
{
Marshal.Copy(new IntPtr(p), output, offset, 4);
}
}
public override void SetNextNumber(byte[] input, int offset)
{
_v = unchecked((int)BitConverter.ToUInt32(input, offset));
}
}
}
|
e0278b66801e689e6cd460ac6abda0d138394813
|
C#
|
KudrinAV/SimpleLibrary
|
/WindowsFormsApplication1/Books.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Xml.Serialization;
namespace WindowsFormsApplication1
{
[Serializable()]
public class Book
{
public List<string> AuthorsList;
public string Name { get; set; }
public DateTime RealiseDate;
public string Annotation;
public string ImagePath;
public string Genre;
public string Categuro;
[XmlIgnore()]
public string Authors
{
get
{
if (AuthorsList.Count != 0)
{
string result = AuthorsList[0];
for (var i = 1; i < AuthorsList.Count; i++)
result += (", " + AuthorsList[i]);
return result;
}
else
{
return null;
}
}
set { }
}
[XmlIgnore()]
public string GetRealiseDate
{
get { return RealiseDate.Day.ToString() + "." + RealiseDate.Month.ToString() + "." + RealiseDate.Year.ToString(); }
set { }
}
[XmlIgnore()]
public Bitmap Image { get
{ return new Bitmap(ImagePath); } private set { } }
public Book() { }
public Book(string[] _a, string _n, DateTime _d, string _ann, string _imPath, string _gen, string _cat)
{
AuthorsList = new List<string>();
foreach (var item in _a)
{
AuthorsList.Add(item);
}
Name = _n;
RealiseDate = _d;
Annotation = _ann;
ImagePath = _imPath;
Genre = _gen;
Categuro = _cat;
}
public void BookChanged(string[] _a, string _n, DateTime _d, string _ann, string _imPath, string _gen, string _cat)
{
AuthorsList = new List<string>();
foreach (var item in _a)
{
AuthorsList.Add(item);
}
Name = _n;
RealiseDate = _d;
Annotation = _ann;
ImagePath = _imPath;
Genre = _gen;
Categuro = _cat;
}
~Book() { }
//enum Category { }
}
}
|
24ea44e680e7b9fdc5b82c8afc7d049c95a2929e
|
C#
|
net-radio/net-radio
|
/NetRadio.Devices.G33Ddc/Signal/G3XDdcDdc1StreamProvider.cs
| 2.5625
| 3
|
using System;
using NetRadio.Signal;
namespace NetRadio.Devices.G3XDdc.Signal
{
public class G3XDdcDdc1StreamProvider:IAudioProvider
{
public event EventHandler<ChunkArgs> DataChunkRecieved;
private readonly Ddc1 _ddc1;
public bool SeperateIq { get; private set; }
public int SamplingRate()
{
var iqRate = (int) _ddc1.DdcArgs().Info.SampleRate;
return SeperateIq ? iqRate : iqRate*2;
}
public int Bits()
{
return (int)_ddc1.DdcArgs().Info.BitsPerSample;
}
public int ChannelCount()
{
return SeperateIq ? 2 : 1;
}
public void Start()
{
_ddc1.DataRecieved+=Ddc1_DataRecieved;
}
public void Stop()
{
_ddc1.DataRecieved -= Ddc1_DataRecieved;
}
private void Ddc1_DataRecieved(object sender, Ddc1CallbackArgs e)
{
if (DataChunkRecieved == null)
return;
var iqRate = e.SamplingRate;
iqRate= SeperateIq ? iqRate : iqRate * 2;
DataChunkRecieved(this, new ChunkArgs(e.Data,iqRate));
}
public G3XDdcDdc1StreamProvider(Ddc1 ddc1, bool seperateIq=false)
{
_ddc1 = ddc1;
SeperateIq = seperateIq;
}
}
}
|
951beb6634003e4d4ee31c69ff0ce5ff4a8fe444
|
C#
|
qq157796573/Test
|
/HomeworkTwo.Comm/ExtentsMethonds/ExtentMethond.cs
| 2.734375
| 3
|
using HomeworkTwo.Comm.AttributeExtents;
using HomeworkTwo.Comm.AttributeExtents.Validata;
using HomeworkTwo.Comm.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace HomeworkTwo.Comm.ExtentsMethonds
{
/// <summary>
/// 使用扩展方法类
/// </summary>
public static class ExtentMethond
{
#region 枚举中文名称
/// <summary>
/// 获取枚举特性的名称,没有就放回当前属性名称
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static string GetEnumName(this Enum value)
{
Type type = value.GetType();
string name = value.ToString();
var fieid = type.GetField(name);
if (fieid.IsDefined(typeof(NameAttribute), true))
{
foreach (var attribute in fieid.GetCustomAttributes(true))
{
if (attribute is NameAttribute)
{
NameAttribute nameAttribute = (NameAttribute)attribute;
name = nameAttribute.Name;
}
}
}
return name;
}
#endregion
#region 测试数据
public static string MyLabelFor<TModel, TValue>(Expression<Func<TModel, TValue>> expression)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
MemberExpression memberExpression = (MemberExpression)expression.Body;
PropertyInfo propertyInfo = memberExpression.Member as PropertyInfo;
return propertyInfo.GetDisplayName();
}
#endregion
#region 获取属性中文名称
/// <summary>
/// 获取中文名称
/// </summary>
/// <param name="property">当前中文名称</param>
/// <returns></returns>
public static string GetDisplayName<T>(Func<T> func) where T : class,new()
{
T t = new T();
return "";
//Type type
//return func.Invoke();
//string name;
//if (MyCache.GetCache($"property{property.Name}") == null)
//{
// Type attributeType = typeof(DisplayNameAttribute);
// name = property.Name;
// foreach (var attribute in property.GetCustomAttributes(true))
// {
// DisplayNameAttribute displayNameAttribute = attribute as DisplayNameAttribute;
// if (displayNameAttribute != null)
// {
// name = displayNameAttribute.Name;
// break;
// }
// }
// MyCache.SetCache($"property{property.Name}", name);
//}
//else
//{
// name = MyCache.GetCache($"property{property.Name}").ToString();
//}
//return name;
}
#endregion
#region 获取属性中文名称
/// <summary>
/// 获取中文名称
/// </summary>
/// <param name="property">当前中文名称</param>
/// <returns></returns>
public static string GetDisplayName(this PropertyInfo property)
{
Type attributeType = typeof(DisplayNameAttribute);
string name = property.Name;
foreach (var attribute in property.GetCustomAttributes(true))
{
DisplayNameAttribute displayNameAttribute = attribute as DisplayNameAttribute;
if (displayNameAttribute != null)
{
name = displayNameAttribute.Name;
break;
}
}
return name;
}
#endregion
#region 获取数据库对应字段名称
public static string GetPropName(this PropertyInfo propertyInfo)
{
string name;
if (MyCache.GetCache($"propertyInfo{propertyInfo.Name}") == null)
{
name = propertyInfo.Name;
Type attributeType = typeof(NameAttribute);
NameAttribute nameAttribute = propertyInfo.GetCustomAttribute(attributeType, true) as NameAttribute;
if (nameAttribute != null)
name = nameAttribute.Name;
MyCache.SetCache($"propertyInfo{propertyInfo.Name}", name);
}
else
{
name = MyCache.GetCache($"propertyInfo{propertyInfo.Name}").ToString();
}
return name;
}
#endregion
#region 获取类类名
public static string GetClassName<T>(this T t) where T : class
{
string name;
if (MyCache.GetCache($"Class{typeof(T).Name}") == null)
{
Type type = typeof(T);
name = type.Name;
NameAttribute nameAttribute = type.GetCustomAttribute(typeof(NameAttribute), true) as NameAttribute;
if (nameAttribute != null)
name = nameAttribute.Name;
MyCache.SetCache($"Class{typeof(T).Name}", name);
}
else
{
name = MyCache.GetCache($"Class{typeof(T).Name}").ToString();
}
return name;
}
public static IEnumerable<ValidataErrorModel> Validata<T>(this T t) where T : BaseModel
{
Type type = typeof(T);
List<ValidataErrorModel> validataErrorModels = validataErrorModels = new List<ValidataErrorModel>();
foreach (PropertyInfo prop in type.GetProperties())
{
if (prop.IsDefined(typeof(AbstractValidataAttribute), true))
{
IEnumerable<AbstractValidataAttribute> abstractValidataAttribute = prop.GetCustomAttributes<AbstractValidataAttribute>(true) as IEnumerable<AbstractValidataAttribute>;
foreach (var validataAttribute in abstractValidataAttribute)
{
//validataErrorModels.Add(validataAttribute.Validata(prop.GetValue(t)));
ValidataErrorModel validataErrorModel = validataAttribute.Validata(prop.GetValue(t));
if (validataErrorModel.IsError) //只返回错误信息
{
validataErrorModel.ErrorMsg = prop.GetDisplayName() + validataErrorModel.ErrorMsg;
validataErrorModels.Add(validataErrorModel);
//yield return validataErrorModel;
}
}
}
}
return validataErrorModels;
}
#endregion
}
}
|
096a37cd9aeba65b6e8352c7ecff2344e390627b
|
C#
|
VladymyrB/CS-Sem2
|
/Lab7/Program.cs
| 3.203125
| 3
|
using System;
using System.IO;
namespace Lab7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(FileManager.GetMaxHierarchyDirectories(@"C:\Users\38095\Desktop\dut\CS Rep\lab7"));
}
}
public class FileManager
{
public static void CreateDirectories(string calalogPath)
{
for (int i = 0; i < 100; i++)
{
Directory.CreateDirectory(Path.Combine(calalogPath, $"FOLDER_{i}"));
}
}
public static void DeleteDirectories(string calalogPath)
{
for (int i = 0; i < 100; i++)
{
Directory.Delete(Path.Combine(calalogPath, $"FOLDER_{i}"));
}
}
public static void CreateHierarchyDirectories(string calalogPath)
{
for (int i = 0; i < 100; i++)
{
var path = calalogPath;
for (int j = 0; j <= i; j++)
{
path = Path.Combine(path, $"FOLDER_{j}");
}
Directory.CreateDirectory(path);
}
}
public static int GetMaxHierarchyDirectories(string calalogPath)
{
var path = calalogPath;
var i = 0;
while (true)
{
for (int j = 0; j < i; j++)
{
path = Path.Combine(path, $"FOLDER_{j}");
}
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
return i - 1;
}
i++;
}
}
public static string GetMaxHierarchyDirectory(string calalogPath)
{
var path = calalogPath;
var i = 0;
while (true)
{
for (int j = 0; j < i; j++)
{
path = Path.Combine(path, $"FOLDER_{j}");
}
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{
return $"FOLDER_{i - 1}";
}
i++;
}
}
}
}
|
e93d578edde9d244ed179124204cda4cadb4a965
|
C#
|
wanweihua/ScreenShare-2
|
/ScreenShare/Capture.cs
| 2.875
| 3
|
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using OpenCvSharp;
namespace ScreenShare
{
using Timer = System.Timers.Timer;
using Size = System.Drawing.Size;
/// <summary>
/// プロセス及びデスクトップ画面のキャプチャを行います。
/// </summary>
class Capture
{
/// <summary>
/// キャプチャ時のデータを格納します
/// </summary>
public struct CaptureData
{
/// <summary>
/// キャプチャされた画像
/// </summary>
public IntPtr captureData;
/// <summary>
/// キャプチャサイズ
/// </summary>
public Size captureSize;
/// <summary>
/// Iフレームかどうか
/// </summary>
public bool isIntraFrame;
}
/// <summary>
/// 分割画面のキャプチャ時のデータを格納します
/// </summary>
public struct SegmentCaptureData
{
/// <summary>
/// キャプチャされた領域の識別子
/// </summary>
public int segmentIdx;
/// <summary>
/// キャプチャされた領域
/// </summary>
public Rectangle rect;
/// <summary>
/// キャプチャされた領域のエンコード済みバッファ
/// </summary>
public byte[] encodedFrameBuffer;
}
/// <summary>
/// キャプチャするプロセスを設定、取得します。
/// </summary>
public Process CaptureProcess { get; set; }
/// <summary>
/// キャプチャするデスクトップの領域を設定、取得します。
/// </summary>
public Rectangle CaptureBounds { get; set; }
/// <summary>
/// キャプチャに領域を使用するかどうかを設定、取得します。
/// </summary>
public bool UseCaptureBounds { get; set; }
/// <summary>
/// キャプチャした画面のスケーリング値を設定、取得します。
/// </summary>
public float Scale { get; set; }
/// <summary>
/// キャプチャを行う頻度(fps)を設定、取得します。
/// </summary>
public int FramesPerSecond { get; set; }
/// <summary>
/// キャプチャした画面のエンコード形式を文字列で設定、取得します。デフォルトは ".jpg" です。
/// </summary>
public string EncodeFormatExtension
{
get
{
return m_EncodeFormatExtension;
}
set
{
m_EncodeFormatExtension = value;
switch (m_EncodeFormatExtension)
{
case ".jpg":
m_EncodingParam.EncodingId = ImwriteFlags.JpegQuality;
break;
case ".png":
m_EncodingParam.EncodingId = ImwriteFlags.PngCompression;
break;
default:
m_EncodingParam.EncodingId = ImwriteFlags.JpegQuality;
break;
}
}
}
/// <summary>
/// キャプチャした画面のエンコード品質を設定、取得します。デフォルトは 95 です。
/// </summary>
public int EncoderQuality
{
get
{
return m_EncodeQuality;
}
set
{
m_EncodeQuality = value;
m_EncodingParam.Value = value;
}
}
/// <summary>
/// キャプチャした画面の、差分の割合(異なる画素の数)が画素総数の何割かを超えた場合に元画像として得るかの割合を設定、取得します。デフォルトは 0.25f です。
/// </summary>
public float DiffFrameRatio
{
get
{
return m_DiffFrameRatio;
}
set
{
if (value < 0.0f || value > 1.0f)
throw new ArgumentOutOfRangeException();
m_DiffFrameRatio = value;
}
}
/// <summary>
/// キャプチャ画面を分割する縦、横の分割数を設定、取得します。デフォルトは 3 です。
/// </summary>
public int CaptureDivisionNum { get; set; }
/// <summary>
/// キャプチャする全体のサイズを取得します。
/// </summary>
public Size CaptureSize { get; private set; }
/// <summary>
/// キャプチャ後のスケールされたサイズを取得します。
/// </summary>
public Size ScaledCaptureSize { get; private set; }
/// <summary>
/// 画面がキャプチャされた時に発生します。
/// </summary>
public event EventHandler<CaptureData> Captured;
/// <summary>
/// 分割画面がキャプチャされた時に発生します。
/// </summary>
public event EventHandler<SegmentCaptureData> SegmentCaptured;
/// <summary>
/// 例外が発生した際に発生します。
/// </summary>
public event EventHandler<Exception> Error;
/// <summary>
/// 現在送信しているかどうかを返します。
/// </summary>
public bool Capturing { get; private set; }
/// <summary>
/// エンコードパラメータ
/// </summary>
private ImageEncodingParam m_EncodingParam = new ImageEncodingParam(ImwriteFlags.JpegQuality, 95);
/// <summary>
/// エンコードフォーマット
/// </summary>
private string m_EncodeFormatExtension = ".jpg";
/// <summary>
/// エンコード品質
/// </summary>
private int m_EncodeQuality = 95;
/// <summary>
/// 差分割合
/// </summary>
private float m_DiffFrameRatio = 0.25f;
/// <summary>
/// Iフレーム
/// </summary>
private Mat m_IntraFrameMat;
/// <summary>
/// キャプチャタイマー
/// </summary>
private Timer m_Timer = new Timer();
/// <summary>
/// キャプチャプロセスハンドル
/// </summary>
private IntPtr m_Handle = IntPtr.Zero;
/// <summary>
/// キャプチャプロセスデバイスコンテキスト
/// </summary>
private IntPtr m_ProcessDC = IntPtr.Zero;
private IntPtr m_Hbmp;
private IntPtr m_Hdc;
private IntPtr m_Bits;
/// <summary>
/// キャプチャする短形
/// </summary>
private Rectangle m_SrcRect;
/// <summary>
/// キャプチャイメージサイズ
/// </summary>
private Size m_DstSize;
/// <summary>
/// キャプチャ状態
/// </summary>
private bool m_IsCapturing = false;
/// <summary>
/// キャプチャタスク
/// </summary>
private Task m_Task;
/// <summary>
/// インスタンスを初期化します。
/// </summary>
public Capture()
{
CaptureBounds = Screen.PrimaryScreen.Bounds;
}
/// <summary>
/// 画面のキャプチャを開始します。
/// </summary>
public void Start()
{
if (CaptureProcess != null && CaptureProcess.HasExited)
Error(this, new ObjectDisposedException(CaptureProcess.ProcessName, "プロセス オブジェクトは既に破棄されています。"));
Capturing = true;
m_IsCapturing = true;
PrepareCapturing();
Debug.Log("Start Capturing");
StartCaptureLoop(1000.0 / FramesPerSecond);
}
/// <summary>
/// キャプチャの停止を待ちます。
/// </summary>
public async void StopAsync(int timeoutms = 1000)
{
m_IsCapturing = false;
if (m_Task == null) return;
await Task.Run(() => m_Task.Wait());
CleanUp();
m_IntraFrameMat = null;
Capturing = false;
Debug.Log("Stop Capturing");
}
/// <summary>
/// キャプチャループスレッド作成
/// </summary>
/// <param name="ms">キャプチャ間隔</param>
private void StartCaptureLoop(double ms = 50)
{
//Parallel.Invoke(() =>
m_Task = Task.Run(() =>
{
var capCnt = 0;
var sw = new Stopwatch();
var mat = new Mat(m_DstSize.Height, m_DstSize.Width, MatType.CV_8UC4, m_Bits);
var mat_xor = new Mat();
var mat_diff = new Mat();
var segRect = new Rectangle(0, 0, m_DstSize.Width / CaptureDivisionNum, m_DstSize.Height / CaptureDivisionNum);
var cData = new CaptureData()
{
captureData = m_Bits,
captureSize = m_DstSize,
isIntraFrame = true,
};
m_IntraFrameMat = new Mat(m_DstSize.Height, m_DstSize.Width, MatType.CV_8UC4);
sw.Start();
while (m_IsCapturing)
{
//Win32.BitBlt(hdc, 0, 0, dstSize.Height, dstSize.Width, m_ProcessDC, 0, 0, Win32.SRCCOPY);
Win32.StretchBlt(m_Hdc, 0, m_DstSize.Height, m_DstSize.Width, -m_DstSize.Height, m_ProcessDC,
m_SrcRect.X, m_SrcRect.Y, m_SrcRect.Width, m_SrcRect.Height, Win32.SRCCOPY);
Captured(this, cData);
try
{
Cv2.BitwiseXor(mat, m_IntraFrameMat, mat_xor);
Cv2.CvtColor(mat_xor, mat_diff, ColorConversionCodes.RGBA2GRAY);
}
catch
{
continue;
}
for (int y = 0; y < CaptureDivisionNum; y++)
{
for (int x = 0; x < CaptureDivisionNum; x++)
{
var segIdx = y * CaptureDivisionNum + x;
segRect.X = segRect.Width * x;
segRect.Y = segRect.Height * y;
var sRect = new Rect(segRect.X, segRect.Y, segRect.Width, segRect.Height);
var segDiff = mat_diff.SubMat(sRect);
var nonZero = segDiff.CountNonZero();
if (nonZero != 0)
{
var segCapture = mat.SubMat(sRect);
var img_buffer = segCapture.ImEncode(EncodeFormatExtension, m_EncodingParam);
var sData = new SegmentCaptureData()
{
segmentIdx = segIdx,
rect = segRect,
encodedFrameBuffer = img_buffer,
};
SegmentCaptured(this, sData);
var segIntra = m_IntraFrameMat.SubMat(sRect);
segCapture.CopyTo(segIntra);
}
}
}
var sleepMs = (ms * capCnt) - sw.Elapsed.TotalMilliseconds;
if (sleepMs > 0) Thread.Sleep((int)sleepMs);
capCnt++;
//Debug.Log(""+capCnt);
//GC.Collect();
//File.WriteAllBytes("dump/"+capCnt+".jpg", mat.ImEncode(EncodeFormatExtension, m_EncodingParam));
}
sw.Stop();
//Win32.SelectObject(hdc, hbmpPrev);
});
}
/// <summary>
/// キャプチャの準備
/// </summary>
private void PrepareCapturing()
{
m_Handle = CaptureProcess != null ? CaptureProcess.MainWindowHandle : IntPtr.Zero;
m_ProcessDC = Win32.GetWindowDC(m_Handle);
m_SrcRect = GetCaptureRect();
m_DstSize = new Size((int)(m_SrcRect.Width * Scale), (int)(m_SrcRect.Height * Scale));
var bmi = new Win32.BITMAPINFO();
var bmiHeader = new Win32.BITMAPINFOHEADER();
bmiHeader.biSize = (uint)Marshal.SizeOf(bmiHeader);
bmiHeader.biWidth = m_DstSize.Width;
bmiHeader.biHeight = m_DstSize.Height;
bmiHeader.biPlanes = 1;
bmiHeader.biBitCount = 32;
bmiHeader.biSizeImage = (uint)(m_DstSize.Width * m_DstSize.Height * 4);
bmi.bmiHeader = bmiHeader;
m_Hbmp = Win32.CreateDIBSection(IntPtr.Zero, ref bmi, Win32.DIB_RGB_COLORS, out m_Bits, IntPtr.Zero, 0);
m_Hdc = Win32.CreateCompatibleDC(IntPtr.Zero);
var hbmpPrev = Win32.SelectObject(m_Hdc, m_Hbmp);
Win32.DeleteObject(hbmpPrev);
Win32.SetStretchBltMode(m_Hdc, Win32.STRETCH_HALFTONE);
}
/// <summary>
/// キャプチャ後始末
/// </summary>
private void CleanUp()
{
Win32.ReleaseDC(IntPtr.Zero, m_ProcessDC);
Win32.DeleteObject(m_Hbmp);
Win32.DeleteDC(m_Hdc);
}
/// <summary>
/// キャプチャ範囲取得
/// </summary>
/// <returns></returns>
private Rectangle GetCaptureRect()
{
var rect = new Rectangle();
if (UseCaptureBounds)
{
rect = CaptureBounds;
}
else if (m_Handle != IntPtr.Zero)
{
Win32.RECT w32rect;
Win32.GetWindowRect(m_Handle, out w32rect);
rect.X = 0;
rect.Y = 0;
rect.Width = w32rect.right - w32rect.left;
rect.Height = w32rect.bottom - w32rect.top;
if (rect.Width == 0 || rect.Height == 0)
{
Error(this, new ArgumentException(CaptureProcess.ProcessName, "無効なプロセスです。"));
}
}
else
{
rect = Screen.PrimaryScreen.Bounds;
}
return rect;
}
}
}
|
09bfd39601452a8b2b0c76ad26740d1cded1ad99
|
C#
|
BlueSunGaming/DungeonAlpha
|
/Assets/RPGAIO/Scripts/Core/Characters/VitalHandling/CombatCalculator.cs
| 2.765625
| 3
|
namespace LogicSpawn.RPGMaker.Core
{
public class CombatCalculator
{
private static readonly CombatCalculator MyInstance = new CombatCalculator();
private const int MaxEvadeRange = 1000;
private const float MaxEvadeBonus = 0.25f;
private const float BaseAccuracy = 0.60f;
public static CombatCalculator Instance
{
get { return MyInstance; }
}
public AccuracyCheck AccuracyCheck(float accuracy, float evasion)
{
var accuracyCheck = new AccuracyCheck {AccuracyIsHigher = accuracy > evasion};
var range = accuracyCheck.AccuracyIsHigher ? accuracy - evasion : evasion - accuracy;
var evasionAccuracyBonus = range / MaxEvadeRange * MaxEvadeBonus;
accuracyCheck.PercentageChance = BaseAccuracy + evasionAccuracyBonus;
return accuracyCheck;
}
public float GetDamageReductionPercent(float characterArmor, int physicalDamage)
{
//1 Point of damage reduced for every 10 points of armour
var reduction = characterArmor / (characterArmor + (10 * physicalDamage));
return reduction;
}
}
}
|
a2dd713438bb1c9b698072c87604e01b7c6db2bd
|
C#
|
tmilar/encuentrame
|
/Web/NailsSupports/Nails.Tests/Persistence/NHibernate/TestModel/Country.cs
| 2.734375
| 3
|
using System.Collections.Generic;
using System.Linq;
using NailsFramework.Persistence;
using NailsFramework.Tests.Persistence.Common;
namespace NailsFramework.Tests.Persistence.NHibernate.TestModel
{
public class Country : Model<Country>, ICountry<City>
{
public Country()
{
Cities = new List<City>();
}
public virtual IList<City> Cities { get; protected set; }
#region ICountry<City> Members
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual IEnumerable<City> CitiesStartingWith(string start)
{
return QueryCollection(x => x.Cities).Where(x => x.Name.StartsWith(start));
}
public virtual void AddCity(string name)
{
Cities.Add(new City {Name = name});
}
#endregion
public virtual IQueryable<City> QueryCities()
{
return QueryCollection(x => x.Cities);
}
public virtual void RemoveCity(City city)
{
Cities.Remove(city);
}
}
}
|
e7f0ad88f4de9381ee0a974bc074d893ce2fd308
|
C#
|
ProjectSharing/JQCore
|
/JQCore/Serialization/DefaultBinarySerializer.cs
| 2.75
| 3
|
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
namespace JQCore.Serialization
{
/// <summary>
/// Copyright (C) 2017 yjq 版权所有。
/// 类名:DefaultBinarySerializer.cs
/// 类属性:公共类(非静态)
/// 类功能描述:DefaultBinarySerializer
/// 创建标识:yjq 2017/9/4 22:11:27
/// </summary>
public class DefaultBinarySerializer : IBinarySerializer
{
private readonly BinaryFormatter _binaryFormatter = new BinaryFormatter();
/// <summary>
/// 反序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="serializedObject">字节数组</param>
/// <returns>对象</returns>
public T Deserialize<T>(byte[] serializedObject)
{
using (var stream = new MemoryStream(serializedObject))
{
return (T)_binaryFormatter.Deserialize(stream);
}
}
/// <summary>
/// 异步反序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="serializedObject">字节数组</param>
/// <returns>对象</returns>
public Task<T> DeserializeAsync<T>(byte[] serializedObject)
{
return Task.FromResult(Deserialize<T>(serializedObject));
}
/// <summary>
/// 序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="item">对象值</param>
/// <returns>字节数组</returns>
public byte[] Serialize<T>(T item)
{
using (var stream = new MemoryStream())
{
_binaryFormatter.Serialize(stream, item);
return stream.ToArray();
}
}
/// <summary>
/// 异步序列化
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="item">对象值</param>
/// <returns>字节数组</returns>
public Task<byte[]> SerializeAsync<T>(T item)
{
return Task.FromResult(Serialize<T>(item));
}
}
}
|
7739afd8ac536434674f989c3a439c3886d59527
|
C#
|
chenboyi081/CsharpBase
|
/S205 属性/C02Demo/Car.cs
| 3.265625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace C02Demo
{
class Car
{
// 轮子数量 颜色 价格 型号 座位数量 字段,
public int wheelNum;
public string color;
public decimal price;
public string model;
public int seatNum;
public string brand;
public void Run()
{
Console.WriteLine("我在行驶...");
}
public void Stop()
{
Console.WriteLine("我停止了");
}
//还有1个自己介绍自己的方法(显示自己的品牌 轮子 颜色 价格 型号 座位。。信息.);
public void SayHi()
{
Console.WriteLine("大家好,我是1个{0}汽车,型号是{1},颜色是{2},价格是{3},轮子有{4}个,座位有{5}个",
brand,
model,
color,
price,
wheelNum,
seatNum
);
}
}
}
|
a3ad338ed1a81f5d002447807dc44df7e8f1a919
|
C#
|
snovader/Lean
|
/Algorithm.CSharp/Dev/RCNet/Neural/Data/PatternBundle.cs
| 3.03125
| 3
|
using System;
using System.Collections.Generic;
using RCNet.Extensions;
namespace RCNet.Neural.Data
{
/// <summary>
/// Bundle of pattern and desired output vector
/// </summary>
[Serializable]
public class PatternBundle
{
//Attributes
/// <summary>
/// Collection of input patterns
/// </summary>
public List<List<double[]>> InputPatternCollection { get; }
/// <summary>
/// Collection of output vectors (desired values)
/// </summary>
public List<double[]> OutputVectorCollection { get; }
//Constructors
/// <summary>
/// Instantiates data bundle.
/// Creates shallow copy of given lists
/// </summary>
/// <param name="inputPatternCollection">Collection of input patterns</param>
/// <param name="outputVectorCollection">Collection of output vectors</param>
public PatternBundle(List<List<double[]>> inputPatternCollection, List<double[]> outputVectorCollection)
{
InputPatternCollection = new List<List<double[]>>(inputPatternCollection);
OutputVectorCollection = new List<double[]>(outputVectorCollection);
return;
}
/// <summary>
/// Instantiates data bundle
/// </summary>
public PatternBundle()
{
InputPatternCollection = new List<List<double[]>>();
OutputVectorCollection = new List<double[]>();
return;
}
/// <summary>
/// Adds pattern/vector pair into the bundle
/// </summary>
/// <param name="pattern">Input pattern of vectors</param>
/// <param name="outputVector">Output vector (ideal)</param>
public void AddPair(List<double[]> pattern, double[] outputVector)
{
InputPatternCollection.Add(pattern);
OutputVectorCollection.Add(outputVector);
return;
}
/// <summary>
/// Shuffles stored pairs
/// </summary>
/// <param name="rand">Random object</param>
public void Shuffle(System.Random rand)
{
List<List<double[]>> l1 = new List<List<double[]>>(InputPatternCollection);
List<double[]> l2 = new List<double[]>(OutputVectorCollection);
InputPatternCollection.Clear();
OutputVectorCollection.Clear();
int[] shuffledIndices = new int[l2.Count];
shuffledIndices.ShuffledIndices(rand);
for (int i = 0; i < shuffledIndices.Length; i++)
{
InputPatternCollection.Add(l1[shuffledIndices[i]]);
OutputVectorCollection.Add(l2[shuffledIndices[i]]);
}
return;
}
}//PatternBundle
}//Namespace
|
a922b0ab45786a9ac65396fba3873bbf0eb65279
|
C#
|
Thrapis/DataBaseCourseWork
|
/MobileOperatorApplication/Data/DataGeneration.cs
| 2.578125
| 3
|
using MobileOperatorApplication.Model;
using MobileOperatorApplication.Oracle;
using MobileOperatorApplication.Repository;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MobileOperatorApplication.Data
{
public static class DataGeneration
{
public static int GenerateAllData()
{
int generated = 0;
Console.WriteLine("Generation of Posts");
generated += GeneratePosts();
Console.WriteLine("Generation of Tariff Plans");
generated += GenerateTariffPlans();
Console.WriteLine("Generation of Service Descriptions");
generated += GenerateServiceDescriptions();
Console.WriteLine("Generation of Clients");
generated += GenerateClients(10000);
Console.WriteLine("Generation of Employees");
generated += GenerateEmployees(200);
Console.WriteLine("Generation of Contracts");
generated += GenerateContracts(12000);
Console.WriteLine("Generation of Services");
generated += GenerateServices(0, 7);
Console.WriteLine("Generation of Phone Numbers");
generated += GeneratePhoneNumbers();
Console.WriteLine("Generation of Calls");
generated += GenerateCalls(50000);
Console.WriteLine("Generation of Payments");
generated += GeneratePayments();
return generated;
}
public static int GetAllDataCount()
{
OracleProvider oracleProvider = new OracleProvider();
int count = 0;
count += new CallRepository(oracleProvider).GetAll().Count();
count += new ClientRepository(oracleProvider).GetAll().Count();
count += new ContractRepository(oracleProvider).GetAll().Count();
count += new DebitRepository(oracleProvider).GetAll().Count();
count += new EmployeeRepository(oracleProvider).GetAll().Count();
count += new PaymentRepository(oracleProvider).GetAll().Count();
count += new PhoneNumberRepository(oracleProvider).GetAll().Count();
count += new PostRepository(oracleProvider).GetAll().Count();
count += new ServiceDescriptionRepository(oracleProvider).GetAll().Count();
count += new ServiceRepository(oracleProvider).GetAll().Count();
count += new TariffPlanRepository(oracleProvider).GetAll().Count();
return count;
}
public static int GeneratePosts()
{
int inserted = 0;
PostRepository repository = new PostRepository();
inserted += repository.Insert(new Post("Senior manager", "First")) != -1 ? 1 : 0;
inserted += repository.Insert(new Post("Cashier", "Second")) != -1 ? 1 : 0;
inserted += repository.Insert(new Post("Manager", "Third")) != -1 ? 1 : 0;
return inserted;
}
private static string GetRandomPassportNumber(Random rand)
{
string alph = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string nums = "0123456789";
string result = "";
result += alph[rand.Next(0, alph.Length)];
result += alph[rand.Next(0, alph.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
result += nums[rand.Next(0, nums.Length)];
return result;
}
public static int GenerateClients(int count)
{
string firstnames_path = @"E:\Study\BD_Course_Work\DataForGeneration\firstnames.txt";
string lastnames_path = @"E:\Study\BD_Course_Work\DataForGeneration\lastnames.txt";
string firstnames_string = "";
string lastnames_string = "";
int inserted = 0;
using (StreamReader sr = new StreamReader(firstnames_path))
{
firstnames_string = sr.ReadToEnd();
}
using (StreamReader sr = new StreamReader(lastnames_path))
{
lastnames_string = sr.ReadToEnd();
}
firstnames_string = firstnames_string.Replace("\r\n", ";");
lastnames_string = lastnames_string.Replace("\n", ";");
List<string> firstnames_list = new List<string>(firstnames_string.Split(';'));
List<string> lastnames_list = new List<string>(lastnames_string.Split(';'));
Random rand = new Random();
OracleProvider provider = new OracleProvider();
ClientRepository repository = new ClientRepository();
for (int i = 0; i < count; i++)
{
string firstname = firstnames_list[rand.Next(0, firstnames_list.Count)];
string lastname = lastnames_list[rand.Next(0, lastnames_list.Count)];
string fullname = firstname + " " + lastname;
string login = firstname.ToLower() + "_" + lastname.ToLower();
int ins = provider.CreateAccount(login, "12345", 1);
while (ins != 1)
{
login += rand.Next(0, 10).ToString();
ins = provider.CreateAccount(login, "12345", 1);
}
Client client = new Client(fullname, GetRandomPassportNumber(rand), login);
inserted += repository.Insert(client) != -1 ? 1 : 0;
}
return inserted;
}
public static int GenerateTariffPlans()
{
int inserted = 0;
TariffPlanRepository repository = new TariffPlanRepository();
inserted += repository.Insert(new TariffPlan("Безлимитище+", 25.58f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Супер 10", 21.50f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Супер 25", 30.60f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Супер", 10.81f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Супер GO", 8.84f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("ULTRA", 55.09f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Абсолют", 149.14f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Легко сказать", 0.66f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Особый", 1.23f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Детский", 1.19f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Близкий", 0.66f)) != -1 ? 1 : 0;
inserted += repository.Insert(new TariffPlan("Победа", 1.00f)) != -1 ? 1 : 0;
return inserted;
}
public static int GenerateServiceDescriptions()
{
int inserted = 0;
ServiceDescriptionRepository repository = new ServiceDescriptionRepository();
inserted += repository.Insert(new ServiceDescription("3 телефона", "3 номера телефона, которые позволят пользоваться вашим тарифным планом, указанным в договоре.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("USSD-расписание транспорта", "Сервис позволит вам получать информацию о времени до прибытия общественного транспорта на остановочны пункт.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Сервис «Parkme»", "Сервис предоставляет абонентам возможность совершить с помощью отправки SMS-сообщения или" +
" в процессе пользования мобильным приложением юридически значимые действия, необходимые для заказа и оплаты временного возмездного пользования абонентом свободного места" +
" на платной парковке.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Сервис «Парковка»", "Сервис предоставляет абонентам возможность оплатить парковку своего автомобиля с помощь отправки SMS-, USSD-" +
" запроса или в процессе пользования мобильным приложением.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Семья под присмотром", "Благодаря услуге «Семья под присмотром» каждый родитель перестанет постоянно гадать, где сейчас находится" +
" ребенок: в школе, на тренировке, на прогулке с друзьями или в гостях у бабушки. Услуга «Семья под присмотром» позволяет вам определять местоположение ребенка и узнавать, по какому адресу" +
" он находится прямо сейчас.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Локатор", "Локатор — это простая возможность определения местоположения абонентов: твоих друзей и близких. Ты прямо сейчас можешь узнать," +
" где находятся твои друзья и близкие.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Уроки английского", "Сервис «Портал по изучению английского языка позволяет абонентам при помощи простого SMS-интерфейса, WAP-интерфейса," +
" а также приложения изучать английские слова, также абонентам предоставляется возможность изучение правил грамматики английского языка с помощью видеороликов на WAP-портале." +
" Чтобы воспользоваться сервисом, вам необходимо оформить подписку.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Уроки русского", "Сервис «Уроки русского» поможет вам совершенствовать знания русского языка. Предусмотрена возможность использования" +
" сервиса в качестве толкового словаря. Ежедневно сервис в простой игровой форме посредством SMS сообщений предлагает ответить на интересные вопросы, посвященные грамматике, лексике и фразеологии.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Уроки польского", "Сервис «Уроки польского» поможет вам совершенствовать знания польского языка и подготовится к" +
" собеседованию на получение Карты поляка. Обучение производится при помощи простого SMS-интерфейса. Предусмотрена возможность использования сервиса в качестве переводчика." +
" Вы можете самостоятельно выбрать тему обучения.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Родная мова", "Сервис «Родная мова» помогает абонентам совершенствовать знания белорусского языка. Изучение белорусских слов" +
" производится при помощи простого SMS-интерфейса или WAP-интерфейса. Предусмотрена возможность использования сервиса в качестве переводчика.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("SMS-ИТОГИ", "SMS-ИТОГИ — услуга, позволяющая с помощью SMS-запроса получать результаты репетиционного и централизованного тестирования.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Премиум-контент в образовательных сервисах", "Услуга «Премиум-контент в образовательных сервисах» - это доступ к расширенному функционалу платформы." +
" Данная платформа обрабатывает и предоставляет в удобном электронном виде информацию об успеваемости учащихся.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Баланс веса", "Сервис «Баланс веса» позволяет абонентам рассчитать индекс массы тела, выбрать подходящую для себя диету, а также получать" +
" ежедневную информацию о пользе продуктов для здорового питания.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Баланс воды", "Сервис «Баланс воды» позволяет абоненту следить за уровнем воды в организме, исходя из индивидуальных параметров: роста," +
" веса, возраста и физической активности. Сервис «Баланс воды» поможет контролировать водный баланс и превратит питье воды в полезную привычку.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Клуб скидок", "Услуга «Клуб скидок» —лучшие скидки города в Вашем телефоне: лучшие рестораны, СПА, салоны красоты," +
" спортивные залы и многое другое со скидками до 90%. Подписчикам услуги не нужно покупать каждый купон по отдельности: пользоваться промокодами можно одновременно" +
" и без всяких ограничений. Главное условие — еженедельная подписка.")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Объявления и реклама", "Размещай объявления в газетах, на радио, телеканалах и интернет-сайтах, а также получай подробную информацию" +
" о рекламируемых посредством СМИ товарах (услугах).")) != -1 ? 1 : 0;
inserted += repository.Insert(new ServiceDescription("Мобильные вакансии", "Услуга «Мобильные вакансии» заключается в предоставлении доступа к информации о новых вакансиях на Портале.")) != -1 ? 1 : 0;
return inserted;
}
public static int GenerateEmployees(int count, float first_part = 0.1f, float second_part = 0.35f, float third_part = 0.55f)
{
int inserted = 0;
string firstnames_path = @"E:\Study\BD_Course_Work\DataForGeneration\firstnames.txt";
string lastnames_path = @"E:\Study\BD_Course_Work\DataForGeneration\lastnames.txt";
string firstnames_string = "";
string lastnames_string = "";
using (StreamReader sr = new StreamReader(firstnames_path))
{
firstnames_string = sr.ReadToEnd();
}
using (StreamReader sr = new StreamReader(lastnames_path))
{
lastnames_string = sr.ReadToEnd();
}
firstnames_string = firstnames_string.Replace("\r\n", ";");
lastnames_string = lastnames_string.Replace("\n", ";");
List<string> firstnames_list = new List<string>(firstnames_string.Split(';'));
List<string> lastnames_list = new List<string>(lastnames_string.Split(';'));
Random rand = new Random();
EmployeeRepository repository = new EmployeeRepository();
OracleProvider provider = new OracleProvider();
for (int i = 0; i < count * first_part; i++)
{
string firstname = firstnames_list[rand.Next(0, firstnames_list.Count)];
string lastname = lastnames_list[rand.Next(0, lastnames_list.Count)];
string fullname = firstname + " " + lastname;
string login = firstname.ToLower() + "_" + lastname.ToLower();
int ins = provider.CreateAccount(login, "Password3", 3);
while (ins != 1)
{
login += rand.Next(0, 10).ToString();
ins = provider.CreateAccount(login, "Password3", 3);
}
Employee employee = new Employee(fullname, 1, login);
inserted += repository.Insert(employee) != -1 ? 1 : 0;
}
for (int i = 0; i < count * second_part; i++)
{
string firstname = firstnames_list[rand.Next(0, firstnames_list.Count)];
string lastname = lastnames_list[rand.Next(0, lastnames_list.Count)];
string fullname = firstname + " " + lastname;
string login = firstname.ToLower() + "_" + lastname.ToLower();
int ins = provider.CreateAccount(login, "Password2", 2);
while (ins != 1)
{
login += rand.Next(0, 10).ToString();
ins = provider.CreateAccount(login, "Password2", 2);
}
Employee employee = new Employee(fullname, 2, login);
inserted += repository.Insert(employee) != -1 ? 1 : 0;
}
for (int i = 0; i < count * third_part; i++)
{
string firstname = firstnames_list[rand.Next(0, firstnames_list.Count)];
string lastname = lastnames_list[rand.Next(0, lastnames_list.Count)];
string fullname = firstname + " " + lastname;
string login = firstname.ToLower() + "_" + lastname.ToLower();
int ins = provider.CreateAccount(login, "Password1", 2);
while (ins != 1)
{
login += rand.Next(0, 10).ToString();
ins = provider.CreateAccount(login, "Password1", 2);
}
Employee employee = new Employee(fullname, 3, login);
inserted += repository.Insert(employee) != -1 ? 1 : 0;
}
return inserted;
}
public static int GenerateContracts(int count)
{
int inserted = 0;
IEnumerable<TariffPlan> tariff_plans = new TariffPlanRepository().GetAll();
IEnumerable<Client> clients = new ClientRepository().GetAll();
IEnumerable<Employee> employees = new EmployeeRepository().GetAll();
ContractRepository repository = new ContractRepository();
if (tariff_plans.Count() == 0 || employees.Count() == 0 || clients.Count() == 0)
throw new Exception("Can't generate contracts");
Random rand = new Random();
for (int i = 0; i < count; i++)
{
TariffPlan tariff_plan = tariff_plans.ElementAt(rand.Next(0, tariff_plans.Count()));
Client client = clients.ElementAt(rand.Next(0, clients.Count()));
Employee employee = employees.ElementAt(rand.Next(0, employees.Count()));
DateTime signing_datetime = DateTime.Now.AddDays(rand.Next(-720, 0));
inserted += repository.Insert(new Contract(tariff_plan.ID, client.ID, employee.ID, signing_datetime)) != -1 ? 1 : 0;
}
return inserted;
}
public static int GenerateServices(int min_serv_count = 0, int max_serv_count = 5)
{
int inserted = 0;
IEnumerable<Contract> contracts = new ContractRepository().GetAll();
IEnumerable<ServiceDescription> serviceDescriptions = new ServiceDescriptionRepository().GetAll();
if (contracts.Count() == 0 || serviceDescriptions.Count() == 0)
throw new Exception("Can't generate services");
ServiceRepository repository = new ServiceRepository();
Random rand = new Random();
for (int i = 0; i < contracts.Count(); i++)
{
Contract contract = contracts.ElementAt(i);
SortedSet<int> service_descriptions = new SortedSet<int>();
int serv_count = rand.Next(min_serv_count, max_serv_count + 1);
while (service_descriptions.Count < serv_count)
{
service_descriptions.Add(serviceDescriptions.ElementAt(rand.Next(0, serviceDescriptions.Count())).ID);
}
for (int j = 0; j < service_descriptions.Count; j++)
{
float amount = (float)(rand.NextDouble() * 5 + 2.5);
DateTime disconnect = DateTime.Now.AddDays(rand.NextDouble() * 90 + 1);
DateTime connect = disconnect.AddMonths(-3);
Service service = new Service(contract.ID, service_descriptions.ElementAt(j), amount, connect, disconnect);
inserted += repository.Insert(service) != -1 ? 1 : 0;
}
}
return inserted;
}
private static string GetRandomPhoneNumber(Random rand)
{
string nums = "0123456789";
string result = "+375";
for (int i = 0; i < 9; i++)
{
result += nums[rand.Next(0, nums.Length)];
}
return result;
}
public static int GeneratePhoneNumbers()
{
int inserted = 0;
IEnumerable<Contract> contracts = new ContractRepository().GetAll();
IEnumerable<Service> services = new ServiceRepository().GetAll();
PhoneNumberRepository repository = new PhoneNumberRepository();
if (contracts.Count() == 0 || services.Count() == 0)
throw new Exception("Can't generate phone numbers");
Random rand = new Random();
for (int i = 0; i < contracts.Count(); i++)
{
int temp_insert = 0;
for (int j = 0; j < services.Count(); j++)
{
if (contracts.ElementAt(i).ID == services.ElementAt(j).ID)
{
if (services.ElementAt(j).DESCRIPTION_ID == 1)
{
while (temp_insert < 3)
temp_insert += repository.Insert(new PhoneNumber(GetRandomPhoneNumber(rand), contracts.ElementAt(i).ID)) != -1 ? 1 : 0;
break;
}
}
}
while (temp_insert < 1)
temp_insert += repository.Insert(new PhoneNumber(GetRandomPhoneNumber(rand), contracts.ElementAt(i).ID));
inserted += temp_insert;
}
return inserted;
}
public static int GenerateCalls(int count)
{
int inserted = 0;
IEnumerable<Contract> contracts = new ContractRepository().GetAll();
if (contracts.Count() == 0)
throw new Exception("Can't generate calls");
CallRepository repository = new CallRepository();
Random rand = new Random();
for (int i = 0; i < count; i++)
{
Contract contract = contracts.ElementAt(rand.Next(0, contracts.Count()));
int contact_id = contract.ID;
TimeSpan talk_time = new TimeSpan(0, rand.Next(0, 24), rand.Next(0, 60), rand.Next(0, 60));
long ticks = (long)(rand.NextDouble() * (double)(DateTime.Now.Ticks - contract.SIGNING_DATETIME.Ticks));
DateTime call_dateTime = contract.SIGNING_DATETIME.AddTicks(ticks);
inserted += repository.Insert(new Call(contact_id, GetRandomPhoneNumber(rand), talk_time, call_dateTime)) != -1 ? 1 : 0;
}
return inserted;
}
public static int GeneratePayments(int max_payments_count = 6, float min_payments = 2.5f, float max_payments = 140f)
{
int inserted = 0;
IEnumerable<Contract> contracts = new ContractRepository().GetAll();
if (contracts.Count() == 0)
throw new Exception("Can't generate calls");
PaymentRepository repository = new PaymentRepository();
Random rand = new Random();
for (int i = 0; i < contracts.Count(); i++)
{
Console.WriteLine("Contract payments: " + i);
Contract contract = contracts.ElementAt(i);
int payments_count = rand.Next(1, max_payments_count);
for (int j = 0; j < payments_count; j++)
{
float payment = (float)rand.NextDouble() * (max_payments - min_payments) + min_payments;
long ticks = (long)(rand.NextDouble() * (double)(DateTime.Now.Ticks - contract.SIGNING_DATETIME.Ticks));
DateTime payment_datetime = contract.SIGNING_DATETIME.AddTicks(ticks);
inserted += repository.Insert(new Payment(contract.ID, payment, payment_datetime)) != -1 ? 1 : 0;
}
}
return inserted;
}
}
}
|
00f515a85e878f62e3217f4bd8f32978b7c2ff57
|
C#
|
RoyMartinez/convertirJSONaObjetos
|
/ConvertirJSONaObjetos/movie.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConvertirJSONaObjetos
{
class movie
{
private string name;
private DateTime releaseDate;
private string[] genres;
public string Name { get => name; set => name = value; }
public DateTime ReleaseDate { get => releaseDate; set => releaseDate = value; }
public string[] Genres { get => genres; set => genres = value; }
}
}
|
417ec2d0b59379e9cf32deeaca6d397f26ca30f9
|
C#
|
knudsjef/CodeSamplesForEmployment
|
/Shape.cs
| 2.953125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/**
* This is an abstract class for a game my friends and I were developing. There were different shapes that all had different abilities
* and this was the base class for the all of the shapes.
*/
namespace Assets.Scripts.Shapes
{
public abstract class Shape
{
public static Animator playerAnimator;
public static float OnGroundDistance = 0.2f;
public int Speed;
public int JumpHeight;
public Collider2D ShapeCollider;
public Sprite ShapeSprite;
public float MoveAdditive = 0;
public Rigidbody2D playerRigid;
/// <summary>
/// Initializes the shape character
/// </summary>
public abstract void InitializeShape();
/// <summary>
/// Enables the collider
/// </summary>
public void Enable()
{
ShapeCollider.enabled = true;
}
/// <summary>
/// Disables the collider
/// </summary>
public void Disable()
{
ShapeCollider.enabled = false;
}
/// <summary>
/// Causes the player to jump
/// </summary>
public virtual void Jump()
{
playerRigid.velocity = new Vector2(playerRigid.velocity.x, JumpHeight);
}
/// <summary>
/// Activiates the shapes specific special ability
/// </summary>
/// <param name="player">The gameobject of the player</param>
public abstract void ActivateSpecial(GameObject player);
/// <summary>
/// Moves the player based on input
/// </summary>
/// <param name="directionMultiplier">The normalized direction</param>
public virtual void Move(float directionMultiplier)
{
playerRigid.velocity = new Vector2((Speed * directionMultiplier) + MoveAdditive, playerRigid.velocity.y);
}
}
}
|
3d4b6d6c80100221c57f69a9e9c1a8db275f860a
|
C#
|
masty123/ParallelBro
|
/Assets/MenuAnimationController.cs
| 2.59375
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MenuAnimationController : MonoBehaviour
{
private Animator boyAnimator;
private Animator girlAnimator;
private int actualTime;
private int timeBeforeBoyGlitch;
private int timeBeforeGirlGlitch;
// Start is called before the first frame update
void Start()
{
boyAnimator = transform.Find("Boy").gameObject.GetComponent<Animator>();
girlAnimator = transform.Find("Girl").gameObject.GetComponent<Animator>();
timeBeforeBoyGlitch = RandomTime();
timeBeforeGirlGlitch = RandomTime();
}
// Update is called once per frame
void Update()
{
actualTime = Mathf.RoundToInt(Time.time);
//Debug.Log(timeBeforeBoyGlitch+" "+actualTime);
if (actualTime == timeBeforeBoyGlitch)
{
boyAnimator.SetTrigger("GlitchTrigger");
timeBeforeBoyGlitch = actualTime + RandomTime();
}
if (actualTime == timeBeforeGirlGlitch)
{
girlAnimator.SetTrigger("GlitchTrigger");
timeBeforeGirlGlitch = actualTime + RandomTime();
}
}
private int RandomTime()
{
return Random.Range(4, 6);
}
}
|
83ece1f3eb89b4ac4b5131bc9567797a0c64fa6f
|
C#
|
areyes986/Lab6-7-OopPrincipals
|
/OopPrincipals/OopPrincipals/Classes/Turtle.cs
| 3.21875
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using OopPrincipals.Interfaces;
namespace OopPrincipals.Classes
{
/// <summary>
/// This is a concrete class that is derived from the reptile class and implements the IAttackPrey interface
/// All the methods return a string specific to the turtle class
/// The diet prop is overridden to be omnivore string
/// </summary>
public class Turtle : Reptiles, IAttackPrey
{
public override string Name { get; set; }
public override string Diet { get; set; } = "Omnivore";
public string SharpTeeth { get; set; }
public string ChasePrey()
{
return "I'm going as fast as i can! So close but yet so far..";
}
public override string Eat()
{
return $"I'm an {Diet},I like to eat strawberries and worms.";
}
public string LeapAtPrey()
{
return "TAKE THAT YOU BERRY.";
}
public override string Sound()
{
return "SNAP!";
}
public string StalkPrey()
{
return "This strawberry doesn't know what's comin... hehe.";
}
}
}
|
a7048d0718ff26a7dc5737c4481d41dd3af0d8d0
|
C#
|
AlanWills/Robbi
|
/Assets/Celeste/Log/HudLog.cs
| 2.671875
| 3
|
using Celeste.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
namespace Celeste.Log
{
[AddComponentMenu("Celeste/Log/Hud Log")]
public class HudLog : Singleton<HudLog>
{
private class HudMessage
{
public Text message;
public float timeAlive;
}
#region Properties and Fields
public Transform textParent;
public GameObject hudMessagePrefab;
public Color infoColour = Color.white;
public Color warningColour = Color.yellow;
public Color errorColour = Color.red;
public float messageLifetime = 3;
[SerializeField]
private int maxMessages = 20;
private List<HudMessage> hudMessages = new List<HudMessage>();
private Stack<Text> cachedMessageInstances = new Stack<Text>();
#endregion
#region Logging Methods
public static void LogInfo(string message)
{
if (Instance != null)
{
Instance.Log(message, Instance.infoColour);
UnityEngine.Debug.Log(message);
}
}
public static void LogInfoFormat(string format, params object[] args)
{
LogInfo(string.Format(format, args));
}
public static void LogWarning(string message)
{
if (Instance != null)
{
Instance.Log(message, Instance.warningColour);
UnityEngine.Debug.LogWarning(message);
}
}
public static void LogWarningFormat(string format, params object[] args)
{
LogWarning(string.Format(format, args));
}
public static void LogError(string message)
{
if (Instance != null)
{
Instance.Log(message, Instance.errorColour);
UnityEngine.Debug.LogError(message);
}
}
public static void LogErrorFormat(string format, params object[] args)
{
LogError(string.Format(format, args));
}
private void Log(string message, Color colour)
{
if (cachedMessageInstances.Count > 0)
{
Text messageText = cachedMessageInstances.Pop();
messageText.text = message;
messageText.color = colour;
messageText.gameObject.SetActive(true);
hudMessages.Add(new HudMessage() { message = messageText, timeAlive = 0 });
}
else
{
UnityEngine.Debug.LogWarningFormat("Hud Message limit reached. Message: {0}", message);
}
}
#endregion
#region Unity Methods
protected override void Awake()
{
base.Awake();
for (int i = 0; i < maxMessages; ++i)
{
GameObject gameObject = GameObject.Instantiate(hudMessagePrefab, textParent);
Text messageText = gameObject.GetComponent<Text>();
gameObject.SetActive(false);
cachedMessageInstances.Push(messageText);
}
Application.logMessageReceived += Application_logMessageReceived;
}
private void OnDestroy()
{
Application.logMessageReceived -= Application_logMessageReceived;
}
private void Update()
{
float deltaTime = Time.deltaTime;
for (int i = hudMessages.Count; i > 0; --i)
{
HudMessage hudMessage = hudMessages[i - 1];
hudMessage.timeAlive += deltaTime;
if (hudMessage.timeAlive > messageLifetime)
{
Text messageText = hudMessage.message;
messageText.text = "";
messageText.gameObject.SetActive(false);
hudMessages.RemoveAt(i - 1);
cachedMessageInstances.Push(messageText);
}
}
}
#endregion
#region Callbacks
private void Application_logMessageReceived(string logString, string stackTrace, LogType type)
{
if (type == LogType.Exception || type == LogType.Assert)
{
LogError(logString);
}
}
#endregion
}
}
|
2a13ce47353aaaabe37b41727c71871cddff17a7
|
C#
|
RoboticPrism/ProjectDeepMine
|
/Assets/Scripts/Tasks/MinerTasks/DeconstructTask.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeconstructTask : MinerTask {
// returns true if the current task is feasible
public override bool TaskAvailable()
{
BuildingBase targetBuilding = target.GetComponent<BuildingBase>();
// can't schedule a deconstruct task if the building is being build or is broken
if (targetBuilding.built && !targetBuilding.broken)
{
return base.TaskAvailable();
}
else
{
return false;
}
}
public static bool TaskAvailable(BuildingBase building)
{
return building.built && !building.broken;
}
// Starts the associtated coroutine on the miner
public override void StartTaskCoroutine(Miner miner)
{
miner.StartCoroutine(miner.DeconstructTask(this.target.GetComponent<BuildingBase>()));
}
}
|
28992eb2f0728eaa3f0d46d320dfed5d5cf30e99
|
C#
|
RylandB/CS495-Capstone-Puma
|
/CS495-Capstone-Puma/DataStructure/BoundingBoxes/BoundingBoxIdentifier.cs
| 2.859375
| 3
|
using System.Dynamic;
namespace CS495_Capstone_Puma.DataStructure.BoundingBoxes
{
public class BoundingBoxIdentifier
{
public int[] Coord = new int[4];
public string Label { get; set; }
public string Id { get; set; }
public BoundingBoxIdentifier(int x, int y, int width, int height, string label, string id)
{
Coord[0] = x;
Coord[1] = y;
Coord[2] = width;
Coord[3] = height;
Label = label;
Id = id;
}
}
}
|
1f678367f30f053f907e574318cae37a4043536c
|
C#
|
Scriptopathe/clank-language
|
/Clank/Generation/Languages/YumlLangage.cs
| 2.6875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Clank.Core.Model.Language;
namespace Clank.Core.Generation.Languages
{
/// <summary>
/// Représente un langage de programmation.
/// Cette classe prend en charge la traduction du code d'un arbre abstrait
/// vers le langage de programmation de destination.
/// </summary>
[LanguageGenerator("yuml")]
public class YumlGenerator : ILanguageGenerator
{
public const string LANG_KEY = "cs";
public const bool PRINT_DEBUG = true;
#region Variables
Clank.Core.Model.ProjectFile m_project;
#endregion
/// <summary>
/// Crée une nouvelle instance de YumlGenerator avec un fichier projet passé en paramètre.
/// </summary>
/// <param name="project"></param>
public YumlGenerator(Clank.Core.Model.ProjectFile project)
{
SetProject(project);
}
public string GenerateInstruction(Instruction inst) { return ""; }
/// <summary>
/// Crée une nouvelle instance de YumlGenerator.
/// </summary>
public YumlGenerator() { }
/// <summary>
/// Définit le projet contenant les informations nécessaires à la génération de code.
/// </summary>
public void SetProject(Model.ProjectFile project)
{
m_project = project;
}
/// <summary>
/// Génère les fichiers du projet à partir de la liste des instructions.
/// </summary>
public List<OutputFile> GenerateProjectFiles(List<Instruction> instructions, string outputDirectory, bool isServer)
{
List<OutputFile> outputFiles = new List<OutputFile>();
List<Instruction> enums = new List<Instruction>();
StringBuilder b = new StringBuilder();
foreach (Model.Language.Instruction inst in instructions)
{
if (inst is Model.Language.ClassDeclaration)
{
Model.Language.ClassDeclaration decl = (Model.Language.ClassDeclaration)inst;
b.AppendLine(GenerateYumlClass(decl));
}
else if(inst is Model.Language.EnumDeclaration)
{
b.AppendLine("[" + ((Model.Language.EnumDeclaration)inst).Name +"{bg:green}]");
}
else
{
m_project.Log.AddWarning("Instruction de type " + inst.GetType().ToString() + " inattendue.", inst.Line, inst.Character, inst.Source);
}
}
// Génère le fichier des enums
outputFiles.Add(new OutputFile(outputDirectory + "/diag.txt", b.ToString()));
return outputFiles;
}
/// <summary>
/// Cherche le type des éléments d'un type de collection donné.
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
ClankTypeInstance SeekElementType(ClankTypeInstance collectionType)
{
if (collectionType.BaseType.JType != JSONType.Array)
return collectionType;
else
return SeekElementType(collectionType.GenericArguments.First());
}
string GenerateYumlClass(ClassDeclaration decl)
{
StringBuilder associations = new StringBuilder();
var vars = decl.Instructions.Where((Instruction inst) =>
{
return inst is VariableDeclarationInstruction;
});
var funcs = decl.Instructions.Where((Instruction inst) =>
{
return inst is FunctionDeclaration;
});
string bgcolor = "white";
if (decl.Name == Core.Model.Language.SemanticConstants.StateClass) bgcolor = "blue";
if (decl.Name.Contains("Entity")) bgcolor = "red";
bgcolor = "{bg:" + bgcolor + "}";
StringBuilder b = new StringBuilder();
b.Append("[" + decl.Name + "|");
foreach(var inst in vars)
{
var varDecl = inst as VariableDeclarationInstruction;
if(varDecl != null)
{
if (varDecl.IsPublic)
b.Append("+");
else
b.Append("-");
b.Append(varDecl.Var.Name + ":" + GenerateTypeInstanceName(varDecl.Var.Type));
b.Append(";");
if (!varDecl.Var.Type.BaseType.IsBuiltIn)
{
if (varDecl.Var.Type.BaseType.JType == JSONType.Array)
{
var elementType = SeekElementType(varDecl.Var.Type);
associations.AppendLine("[" + decl.Name + bgcolor + "]1--*+[" + GenerateTypeInstanceName(elementType) + "]");
}
else
associations.AppendLine("[" + decl.Name + bgcolor +"]1--1+[" + GenerateTypeInstanceName(varDecl.Var.Type) + "]");
}
}
}
b.Append("|");
foreach (var inst in funcs)
{
var funcDecl = inst as FunctionDeclaration;
if (funcDecl != null)
{
if (funcDecl.Func.IsPublic)
b.Append("+");
else
b.Append("-");
b.Append(funcDecl.Func.Name + "(");
foreach(var arg in funcDecl.Func.Arguments)
{
b.Append(arg.ArgName + ":" + GenerateTypeInstanceName(arg.ArgType));
if (arg != funcDecl.Func.Arguments.Last())
b.Append(";");
}
b.Append(")");
b.Append(":" + GenerateTypeInstanceName(funcDecl.Func.ReturnType));
if(inst != funcs.Last())
b.Append(";");
if (!funcDecl.Func.ReturnType.BaseType.IsBuiltIn)
{
if (funcDecl.Func.ReturnType.BaseType.JType == JSONType.Array)
{
var elementType = SeekElementType(funcDecl.Func.ReturnType);
associations.AppendLine("[" + decl.Name + bgcolor + "]1--*+[" + GenerateTypeInstanceName(elementType) + "]");
}
else
associations.AppendLine("[" + decl.Name + bgcolor + "]1--1+[" + GenerateTypeInstanceName(funcDecl.Func.ReturnType) + "]");
}
}
}
b.AppendLine("]");
b.AppendLine(associations.ToString());
return b.ToString();
}
#region Expressions
/// <summary>
/// Génère le code représentant l'instance de type passé en paramètre.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
string GenerateTypeInstanceName(ClankTypeInstance type)
{
if (type.IsGeneric)
{
StringBuilder b = new StringBuilder();
foreach (ClankTypeInstance tArg in type.GenericArguments)
{
b.Append(GenerateTypeInstanceName(tArg));
if (tArg != type.GenericArguments.Last())
b.Append(",");
}
if(!type.BaseType.IsMacro)
return GenerateTypeName(type.BaseType) + "\\<" + b.ToString() + "\\>";
else
{
// Si on a un type macro on va remplacer :
// $(T) => type concerné
string nativeFuncName = GenerateTypeName(type.BaseType);
// Remplace les params génériques par leurs valeurs.
for (int i = 0; i < type.BaseType.GenericArgumentNames.Count; i++)
{
nativeFuncName = nativeFuncName.Replace(SemanticConstants.ReplaceChr + "(" + type.BaseType.GenericArgumentNames[i] + ")",
GenerateTypeInstanceName(type.GenericArguments[i]));
}
return nativeFuncName.Replace("<", "\\<").Replace(">", "\\>");
}
}
return GenerateTypeName(type.BaseType);
}
/// <summary>
/// Génère le code représentant le type passé en paramètre.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
string GenerateTypeName(ClankType type)
{
if(type.IsMacro)
{
// Pour les types macro, on remplace le nom du type par le nom du type natif.
Model.MacroContainer.MacroClass mcClass = m_project.Macros.FindClassByType(type);
if (!mcClass.LanguageToTypeName.ContainsKey(LANG_KEY))
throw new InvalidOperationException("Le nom de la macro classe '" + type.GetFullNameAndGenericArgs() + "' n'est pas renseigné pour le langage '" + LANG_KEY + "'");
string nativeClassName = mcClass.LanguageToTypeName[LANG_KEY];
return mcClass.LanguageToTypeName[LANG_KEY];
}
else
return type.Name;
}
#endregion
}
}
|
313ca1c901e80c8d07919ef98cd1a0a20c148112
|
C#
|
CLAHRCWessex/DistanceFunctions
|
/DistanceFunctions/CentroidDistanceGenerator.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
namespace DistanceFunctions
{
public class CentroidDistanceGenerator
{
protected IDistanceCalculator calculator;
public CentroidDistanceGenerator(IDistanceCalculator calculator)
{
this.calculator = calculator;
}
public List<double> GenerateDistances(DataTable points, EastingNorthingColumnIndexer indexer)
{
var centroid = new GroupCentroid(points, indexer);
var distances = new List<double>();
foreach (DataRow row in points.Rows)
{
distances.Add(this.calculator.Calculate(centroid.GetCentreCoordinates(),
new Coordinate((int)row[indexer.NorthingIndex], (int)row[indexer.EastingIndex])));
}
return distances;
}
/// <summary>
/// Calculates the average distance of points from the centroid in one single pass
/// </summary>
/// <param name="points">Datatable containing northings and eastings</param>
/// <param name="eastingIndex">Zero based column index for eastings</param>
/// <param name="northingIndex">Zero based column index for northings</param>
/// <returns></returns>
public double AverageDistance(DataTable points, EastingNorthingColumnIndexer indexer)
{
var centroid = new GroupCentroid(points, indexer);
double runningTotal = 0;
int nullcases = 0;
foreach (DataRow row in points.Rows)
{
try
{
runningTotal += this.calculator.Calculate(centroid.GetCentreCoordinates(),
new Coordinate(Convert.ToInt32(row[indexer.NorthingIndex]), Convert.ToInt32(row[indexer.EastingIndex])));
}
catch (InvalidCastException)
{
nullcases++;
}
}
return runningTotal/(points.Rows.Count-nullcases);
}
/// <summary>
/// Calculates the distances of each point from the group centroid
/// </summary>
/// <param name="points">Datatable containing northings and eastings</param>
/// <param name="eastingIndex">Zero based column index for eastings</param>
/// <param name="northingIndex">Zero based column index for northings</param>
/// <returns>A list of distances from centroid</returns>
public List<double> GetIndividualDistances(DataTable points, EastingNorthingColumnIndexer indexer)
{
var centroid = new GroupCentroid(points, indexer);
int nullcases = 0;
List<double> results = new List<double>();
foreach (DataRow row in points.Rows)
{
try
{
results.Add(this.calculator.Calculate(centroid.GetCentreCoordinates(),
new Coordinate(Convert.ToInt32(row[indexer.NorthingIndex]), Convert.ToInt32(row[indexer.EastingIndex]))));
}
catch (InvalidCastException)
{
nullcases++;
}
}
return results;
}
}
}
|
f1c7b6d102c82d5de22e05b0d23b2de8f095103f
|
C#
|
azurite-dev/azurite
|
/src/Azurite.Console/ShowCommand.cs
| 2.84375
| 3
|
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Spectre.Cli;
using static Azurite.Console.PrintHelpers;
namespace Azurite.Console
{
public class ShowCommand : CommandBase<ShowCommand.ShowCommandSettings>
{
public class ShowCommandSettings : CommandSettings {
[CommandArgument(0, "<ID>")]
[Description("The ID of the ship to get details for. Check `list by-name` to get an ID for the ship.")]
public string ShipId {get;set;}
[CommandOption("-s|--stat-level")]
[Description("Ship level to get stats for. Supports '0' (base), '100' or '120'.")]
public int StatLevel {get;set;} = -1;
}
public ShowCommand(IShipDataProvider provider) : base(provider)
{
}
public override async Task<int> ExecuteAsync(CommandContext context, ShowCommandSettings settings)
{
var ship = (await _provider.GetShipList()).Where(s => s.Id.Equals(settings.ShipId, System.StringComparison.InvariantCultureIgnoreCase));
if (ship.Count() != 1) {
System.Console.WriteLine($"Requested ship was not found by ID '{settings.ShipId}'.");
return 404;
}
var details = await _provider.GetShipDetails(ship.First());
if (Helpers.IsRetrofit(details.ShipId) && settings.StatLevel == 0) {
settings.StatLevel = -1;
}
return PrintSingleShip(details, statLevel: settings.StatLevel);
}
}
}
|
15e34bc7c877c0915bbee34c423544e70be8810e
|
C#
|
rramesh1/sallikasu
|
/SallikasuServices/Models/GetDestinationModel.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SallikasuServices.Models
{
public class GetDestinationModel
{
nasthaEntities DB { get; set; }
public GetDestinationModel()
{
DB = new nasthaEntities();
}
public List<String> GetState()
{
List<String> tDestinations = (from m in DB.merchants select new (m.state)).Distinct().ToList();
return tDestinations;
}
public List<String> GetCity(String State)
{
List<String> tDestinations = (from m in DB.merchants where m.state == State select new (m.city)).Distinct().ToList();
return tDestinations;
}
public List<String> GetSublocality(String State, String City)
{
List<String> tDestinations = (from m in DB.merchants where m.state == State && m.city == City select new (m.sublocality)).Distinct().ToList();
return tDestinations;
}
}
public class DestinationModel
{
public DestinationModel(String state,String city, String subLocality )
{
State = state;
City = city;
SubLocality = subLocality;
}
public String State { get; set; }
public String City { get; set; }
public string SubLocality { get; set; }
}
}
|
594556090a6a654e5adadcccb9dbef0b118e6113
|
C#
|
Srul1k/priority-changer
|
/app/ppc/Program.cs
| 2.6875
| 3
|
using ppc.Commands;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
namespace ppc
{
static class Program
{
public static readonly string Name = Process.GetCurrentProcess().ProcessName;
static void Main(string[] args)
{
if (args.Length == 0)
{
var help = new HelpCommand();
help.Execute();
return;
}
Invoker invoker = null;
try
{
invoker = ReadInvoker();
}
catch (SerializationException serExc)
{
Console.WriteLine("Serialization Failed");
Console.WriteLine(serExc.Message);
}
catch(FileNotFoundException)
{
Console.WriteLine($"Started recording command history in '{Name}.history.xml'");
}
catch (Exception exc)
{
Console.WriteLine(
$"The read history of commands from '{Name}.history.xml' failed: {0} StackTrace: {1}",
exc.Message, exc.StackTrace);
}
finally
{
invoker ??= new Invoker();
}
int level;
string key;
switch (args.First())
{
case "c":
case "create":
if (!TryParseCpuLevelStringToInt(args.Last(), out level))
{
Console.WriteLine($"Unknown priority level: '{args.Last()}'");
return;
}
key = ExtractingKeyFromArguments(args, 1, 1);
try
{
invoker.SetCommand(new CreateCommand(key, level));
}
catch(ArgumentException ex)
{
Console.WriteLine(ex.Message);
return;
}
break;
case "r":
case "read":
invoker.SetCommand(new ReadAllCommand());
break;
case "u":
case "update":
if (!TryParseCpuLevelStringToInt(args.Last(), out level))
{
Console.WriteLine($"Unknown priority level: '{args.Last()}'");
return;
}
key = ExtractingKeyFromArguments(args, 1, 1);
try
{
invoker.SetCommand(new UpdateCommand(key, level));
}
catch(ArgumentException ex)
{
Console.WriteLine(ex.Message);
return;
}
break;
case "d":
case "delete":
key = ExtractingKeyFromArguments(args, 1, 0);
invoker.SetCommand(new DeleteCommand(key));
break;
case "undo":
try
{
invoker.Undo();
}
catch(InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
catch(ArgumentException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Failed to cancel command");
Console.WriteLine(invoker.GetCommand().ToString());
}
WriteInvoker(invoker);
return;
case "h":
case "help":
invoker.SetCommand(new HelpCommand());
break;
default:
Console.WriteLine($"'{args.First()}' is not a command. See '{Name} help'.");
return;
}
try
{
invoker.Run();
}
catch(ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
WriteInvoker(invoker);
}
private static bool TryParseCpuLevelStringToInt(string value, out int result)
{
if (Enum.TryParse(value, true, out CpuPriorityLevel temp))
{
result = (int)temp;
return true;
}
result = 0;
return false;
}
private static string ExtractingKeyFromArguments(string[] args, int countOfCommandWords, int countOfOtherArgs)
{
var temp = args
.TakeWhile((x, i) => i != args.Length - countOfOtherArgs)
.Skip(countOfCommandWords);
return string.Join(" ", temp);
}
private static Invoker ReadInvoker()
{
using var reader = new FileStream($"{Name}.history.xml", FileMode.Open);
var serializer = new DataContractSerializer(typeof(Invoker));
return (Invoker)serializer.ReadObject(reader);
}
private static void WriteInvoker(Invoker invoker)
{
using var writer = new FileStream($"{Name}.history.xml", FileMode.Create);
var serializer = new DataContractSerializer(typeof(Invoker));
serializer.WriteObject(writer, invoker);
}
}
}
|
8448ecdf4323db0bbead485e419edee809856ba2
|
C#
|
MotorGenerator/Dentist-1
|
/Зубы/Backup/Classes/InsertЛьготьнаяКатегория.cs
| 2.765625
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace Стамотология.Classes
{
/// <summary>
/// Добавляет данные
/// </summary>
class InsertЛьготьнаяКатегория:ICommand
{
private string _льготнаяКатегория;
public InsertЛьготьнаяКатегория(string льготнаяКатегория)
{
_льготнаяКатегория = льготнаяКатегория;
}
public void Execute()
{
string sCon = ConnectionDB.ConnectionString();
//OleDbConnection con = new OleDbConnection(sCon);
string query = "INSERT INTO ЛьготнаяКатегория " +
"([ЛьготнаяКатегория]) VALUES " +
"('" + _льготнаяКатегория + "')";
Query.Execute(query, sCon);
//OleDbCommand com = new OleDbCommand(query, con);
//con.Open();
//com.ExecuteNonQuery();
//con.Close();
}
}
}
|
9bd0c1c7e7df484913031e8f922c57559daaf043
|
C#
|
Fman72/TabModellerMVC
|
/TabModellerMVC/TextualBarsView.cs
| 3.171875
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace TabModellerMVC
{
public partial class TextualBarsForm : Form, ITabModellerView
{
public static String REST_STRING = "Rest for one beat";
//Model for this class.
TabModellerModel tabModellerModel;
/// <summary>
/// The constructor for the textual bar view. Calls the TabModellerView super class constructor.
/// </summary>
/// <param name="tabModellerModel">The model for this view.</param>
public TextualBarsForm(TabModellerModel tabModellerModel)
{
this.tabModellerModel = tabModellerModel;
InitializeComponent();
}
/// <summary>
/// This function updates the GraphicalBarView with new data from the model.
/// </summary>
/// <param name="bars">An array of Bar objects to update the view with.</param>
public void update(List<Bar> bars)
{
List<String> textualBarRepresentation = new List<String>();
//For each bar.
for (int i = 0; i < bars.Count; i++)
{
//Finding length of longest line for each bar.
textualBarRepresentation.Add("Bar " + (i + 1) + ":" + Environment.NewLine);
Bar bar = bars[i];
int longestLength = 0;
foreach (String line in bar.lines)
{
if (line.Length > longestLength)
{
longestLength = line.Length;
}
}
//For each character in a line of the bar.
//Looking for the note in the 4 lines to determine if there is a note to play or if it is a rest.
for (int x = 0; x < longestLength; x++)
{
int currentLine = 0;
try {
if (!Regex.IsMatch(bar.lines[currentLine][x].ToString(), @"\||G|D|A|E|g|d|a|e"))
{
//For each line.
//Iterating through position stringPosition on all 4 strings.
while (currentLine < 4)
{
try {
if (Regex.IsMatch(bar.lines[currentLine][x].ToString(), @"X"))
{
textualBarRepresentation.Add(this.parseSpecialNote(ref x, bar, currentLine));
currentLine++;
}
else if (Regex.IsMatch(bar.lines[currentLine][x].ToString(), @"/|p|h|\\"))
{
textualBarRepresentation.Add(this.parseSymbol(ref x, bar, currentLine));
currentLine++;
}
else if (Regex.IsMatch(bar.lines[currentLine][x].ToString(), @"\d"))
{
textualBarRepresentation.Add(this.parseNote(ref x, bar, currentLine));
currentLine++;
}
else
{
if (currentLine == 3)
{
textualBarRepresentation.Add(REST_STRING);
}
currentLine++;
}
}
catch (IndexOutOfRangeException ex)
{
currentLine = 4;
}
}
}
}
//If index out of range this early means there is a bar with tag.
catch(IndexOutOfRangeException ex)
{
}
}
//Adding a new line at the end of every bar for formatting.
textualBarRepresentation.Add(Environment.NewLine);
}
//Adding textual representation to the text box.
this.barsTextBox.Lines = textualBarRepresentation.ToArray();
}
/// <summary>
/// Finds a note in the tab and increments stringPosition to the next character if it is a double digit note.
/// </summary>
/// <param name="x">The position in the String that is being parsed. Is incremented by this function if a double digit number is parsed.</param>
/// <param name="bar">The bar currently being parsed.</param>
/// <param name="currentLine">The currentLine being parsed.</param>
/// <returns></returns>
public String parseNote(ref int stringPosition, Bar bar, int currentLine)
{
int note = -1;
if (bar.lines[currentLine][stringPosition].ToString().Equals("|"))
{
stringPosition++;
}
//Handle double digit numbers.
if (Regex.IsMatch(bar.lines[currentLine][stringPosition + 1].ToString(), @"\d"))
{
if (Int32.Parse((bar.lines[currentLine][stringPosition].ToString()) + (bar.lines[currentLine][stringPosition + 1].ToString())) < 25)
{
//Note is concatentation of two numbers.
note = Int32.Parse((bar.lines[currentLine][stringPosition].ToString()) + (bar.lines[currentLine][stringPosition + 1].ToString()));
//Skip next number.
stringPosition++;
}
//If two single numbers next to each other treat as singles.
else
{
note = Int32.Parse(bar.lines[currentLine][stringPosition].ToString());
}
}
//If not double digit make note the current digit.
else
{
note = Int32.Parse(bar.lines[currentLine][stringPosition].ToString());
}
return "Play a " + Bar.convertNumberToNote(note, currentLine);
}
public String parseSymbol(ref int stringPosition, Bar bar, int currentLine)
{
Char symbol = bar.lines[currentLine][stringPosition];
//Find the next number for the symbol to interact with.
stringPosition++;
String note = this.parseNote(ref stringPosition, bar, currentLine);
if (symbol.Equals('/'))
{
return "Slide up to play " + note;
}
else if (symbol.Equals('\\'))
{
return "Slide down to play " + note;
}
else if (symbol.Equals('h'))
{
return "Hammer on to play " + note;
}
else
{
return "Pull off to play " + note;
}
}
public String parseSpecialNote(ref int stringPosition, Bar bar, int currentLine)
{
stringPosition++;
return "Play a muted note on the " + Bar.convertNumberToNote(0, currentLine) + " string.";
}
//EVENT HANDLERS
/// <summary>
/// This function runs when this form is closed. It exits the application.
/// </summary>
/// <param name="sender">The sender of this event. In this case the form.</param>
/// <param name="e">The event args for the event.</param>
private void TextualBarsForm_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
|
0ff94776c5835108e41d59fedb2a43f84fd626b7
|
C#
|
derin161/CSE3902Game
|
/Super Metroidvania 3Million/CrossPlatformDesktopProject/Libraries/Collision/Collision Handler/ProjectileEnemyCollision.cs
| 2.5625
| 3
|
using SuperMetroidvania5Million.Libraries.Sprite.Projectiles;
using SuperMetroidvania5Million.Libraries.Sprite.EnemySprites;
using SuperMetroidvania5Million.Libraries.Command;
using SuperMetroidvania5Million.Libraries.Audio;
namespace SuperMetroidvania5Million.Libraries.Collision
{
//Author: Nyigel Spann and Will Floyd
public class ProjectileEnemyCollision
{
public ProjectileEnemyCollision()
{
}
public void HandleCollision(IProjectile projectile, IEnemy enemy)
{
//Cast so we can then determine is it's an ice beam or not, casting will succeed if the first statement is true.
if (projectile is PowerBeam && ((PowerBeam)projectile).IsIceBeam)
{
new EnemyFreezeCommand(enemy).Execute();
}
if (!(projectile is KraidHorn) && !(projectile is KraidMissile))
{
new ProjectileDamageEnemyCommand(projectile, enemy).Execute();
SoundManager.Instance.Projectiles.PowerBeamCollideSound.PlaySound();
projectile.Kill();
}
}
}
}
|
06c735e7482c675955521bf21f134e1feec2daab
|
C#
|
joshjcarrier/OpenAnt.NET
|
/OpenAnt.NET/OpenAnt/Entity/Decorator/Collision/CollisionBaseEntity.cs
| 3.03125
| 3
|
namespace OpenAnt.Entity.Decorator.Collision
{
using Microsoft.Xna.Framework;
/// <summary>
/// Registers common collision logistics.
/// </summary>
public abstract class CollisionBaseEntity : GameEntityDecorator
{
/// <summary>
/// Initializes a new instance of the <see cref="CollisionBaseEntity"/> class.
/// </summary>
/// <param name="entity">
/// The entity to decorate.
/// </param>
protected CollisionBaseEntity(GameEntityBase entity) : base(entity)
{
}
/// <summary>
/// Tests to see if entity collides with another at the given location.
/// </summary>
/// <param name="hitTestLocation">
/// The hit test location.
/// </param>
/// <returns>
/// True if a collision with an entity in the location.
/// </returns>
public override bool IsHitTestCollision(Point hitTestLocation)
{
return this.Position.Contains(hitTestLocation);
}
}
}
|
6d615fdf6ca9f4b33c916d0f2350b4f40adea32c
|
C#
|
RosenUrkov/TelerikAcademyHomeworks
|
/C# Fundamentals/Arrays/Frequent Number/Program.cs
| 3.65625
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Frequent_Number
{
class Program
{
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
List<int> listOfNumbers = new List<int>();
int mostRepeatedNumber = 0;
int currentNumber = 0;
int maxRepeats = 0;
int currentRepeats = 0;
bool isFirst = true;
for (int i = 0; i < number; i++)
{
listOfNumbers.Add(int.Parse(Console.ReadLine()));
}
listOfNumbers.Sort();
for (int i = 0; i < number; i++)
{
if (isFirst)
{
isFirst = false;
currentNumber = listOfNumbers[i];
currentRepeats++;
maxRepeats = currentRepeats;
mostRepeatedNumber = currentNumber;
}
else if (currentNumber == listOfNumbers[i])
{
currentRepeats++;
}
else if (currentNumber != listOfNumbers[i])
{
if (currentRepeats > maxRepeats)
{
maxRepeats = currentRepeats;
mostRepeatedNumber = currentNumber;
}
currentNumber = listOfNumbers[i];
currentRepeats = 1;
}
if (i == number - 1)
{
if (currentRepeats > maxRepeats)
{
maxRepeats = currentRepeats;
mostRepeatedNumber = currentNumber;
}
}
}
Console.WriteLine("{0} ({1} times)", mostRepeatedNumber, maxRepeats);
}
}
}
|
43c8fc045b1ffd7c089d4e10af7e5a7829381d3a
|
C#
|
tboogh/Cassowary.Forms
|
/Cassowary.Forms.UnitTest/UnitTest1.cs
| 2.546875
| 3
|
using Cassoway.Forms.Layout;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Xamarin.Forms;
namespace Cassowary.Forms.UnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var layout = new CassowaryLayout();
var view = new Label();
layout.Children.Add(view);
var rect = new Rectangle(0, 0, 400, 400);
layout.Layout(rect);
Assert.AreEqual(rect.Right, view.Bounds.Right);
}
}
}
|
ce3b09e5dd0008a23c39125f9bbaa18eadcff3f1
|
C#
|
alfman99/ABP2-Escritorio
|
/Proyecto2/BD/ORM_HORARIS_INSTALACIONS.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.Data.Entity.Core;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Proyecto2.BD
{
class ORM_HORARIS_INSTALACIONS
{
public static List<HORARIS_INSTALACIONS> SelectAllHORARIS_INSTALACIONS(ref String mensaje)
{
List<HORARIS_INSTALACIONS> _horaris_instalacions = null;
try
{
_horaris_instalacions = (from p in ORM.bd.HORARIS_INSTALACIONS
select p).ToList();
}
catch (DbUpdateException ex)
{
SqlException sqlEx = (SqlException)ex.InnerException.InnerException;
mensaje = BD.ORM.MensajeError(sqlEx);
}
catch (EntityException ex)
{
SqlException sqlEx = (SqlException)ex.InnerException;
mensaje = BD.ORM.MensajeError(sqlEx);
}
return _horaris_instalacions;
}
public static String InsertHORARIS_INSTALACIONS(TimeSpan hora_inici, TimeSpan hora_fi, int id_instalacio, int id_dia_setmana)
{
HORARIS_INSTALACIONS horari_instalacio = new HORARIS_INSTALACIONS();
horari_instalacio.hora_inici = hora_inici;
horari_instalacio.hora_fi = hora_fi;
horari_instalacio.id_instalacio = id_instalacio;
horari_instalacio.id_dia_setmana = id_dia_setmana;
ORM.bd.HORARIS_INSTALACIONS.Add(horari_instalacio);
return ORM.SaveChanges();
}
public static void DeleteHORARIS_INSTALACIONS(HORARIS_INSTALACIONS horari_instalacions)
{
ORM.bd.HORARIS_INSTALACIONS.Remove(horari_instalacions);
ORM.SaveChanges();
}
public static String UpdateHORARIS_INSTALACIONS(int id, TimeSpan hora_inici, TimeSpan hora_fi, int id_instalacio, int id_dia_setmana)
{
HORARIS_INSTALACIONS horari_instalacio = ORM.bd.HORARIS_INSTALACIONS.Find(id);
horari_instalacio.hora_inici = hora_inici;
horari_instalacio.hora_fi = hora_fi;
horari_instalacio.id_instalacio = id_instalacio;
horari_instalacio.id_dia_setmana = id_dia_setmana;
return ORM.SaveChanges();
}
}
}
|
91622179fade51609b234cc9bb7180add6d5456a
|
C#
|
ahazan/FE21
|
/SEICRY_FE_UYU_9/Objetos/CFEItems.cs
| 2.84375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace SEICRY_FE_UYU_9.Objetos
{
/// <summary>
/// Representa la estructura de cada item (producto o servicio) de un CFE
/// </summary>
[Serializable]
public class CFEItems
{
#region DETALLES DE PRODUCTOS
private int lineNum;
[XmlIgnore]
public int LineNum
{
get { return lineNum; }
set { lineNum = value; }
}
private int numeroLinea;
/// <summary>
/// Número del ítem
/// <para>Tipo: NUM 3</para>
/// </summary>
public int NumeroLinea
{
get
{
if(numeroLinea.ToString().Length > 3)
return int.Parse( numeroLinea.ToString().Substring(0,3));
return int.Parse(numeroLinea.ToString());
}
set { numeroLinea = value; }
}
private int indicadorFacturacion;
public int IndicadorFacturacion
{
get { return indicadorFacturacion; }
set { indicadorFacturacion = value; }
}
//public enum ESIndicadorFacturacion
//{
// ExentoIva = 1,
// GravadoTasaMinima = 2,
// GravadoTasaBasica = 3,
// GravadoOtraTasa = 4,
// /// <summary>
// /// Por ejemplo docenas de trece
// /// </summary>
// EntregaGratuita = 5,
// ProductoServicioNoFacturable = 6,
// ProductoServicioNoFacturableNegativo = 7,
// /// <summary>
// /// Solo para remitos. En área de referencia se debe indicar el N° de remito que ajusta
// /// </summary>
// ItemRebajarRemitos = 8,
// /// <summary>
// /// Solo para resguardos. En área de referencia se debe indicar el N° de resguardo que anular
// /// </summary>
// ItemAnularResguardo = 9,
// ExportacionAsimilidas = 10,
// ImpuestoPercibido = 11,
// IVASuspenso = 12
//}
/// <summary>
/// Indica si el producto o servicio es exento, o a que tasa esta gravado o si corresponde a un concepto no facturable.
/// <para>Tipo: NUM 2</para>
/// </summary>
//[XmlIgnore]
//public ESIndicadorFacturacion IndicadorFacturacion { get; set; }
//public int IndicadorFacturacionInt
//{
// get { return (int)IndicadorFacturacion; }
// set { IndicadorFacturacion = (ESIndicadorFacturacion)value; }
//}
public enum ESIndicadorAgenteResponsable
{
Responsable = 'R',
NoResponsable = ' ',
}
/// <summary>
/// Obligatorio para agentes/responsables, indica para cada transacción si es agente/responsable del producto que está vendiendo.
/// <para>Tipo: ALFA 1</para>
/// </summary>
[XmlIgnore]
public ESIndicadorAgenteResponsable IndicadorResponsable { get; set; }
public char IndicadorResponsableInt
{
get { return (char)IndicadorResponsable; }
set { IndicadorResponsable = (ESIndicadorAgenteResponsable)value; }
}
private string nombreItem = "";
/// <summary>
/// Nombre del producto o servicio.
/// <para>Tipo: ALFA 80</para>
/// </summary>
public string NombreItem
{
get
{
if(nombreItem.Length > 80)
return nombreItem.Substring(0,80);
return nombreItem;
}
set { nombreItem = value; }
}
private string descripcionItem = "";
/// <summary>
/// Descripción Adicional del producto o servicio. Se utiliza para pack, servicios con detalle.
/// <para>Tipo: ALFA 1000</para>
/// </summary>
public string DescripcionItem
{
get
{
if(descripcionItem.Length > 1000)
return descripcionItem.Substring(0,1000);
return descripcionItem;
}
set { descripcionItem = value; }
}
private double cantidadItem = 0;
/// <summary>
/// Cantidad del ítem.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double CantidadItem
{
get
{
if(cantidadItem.ToString().Length > 17)
return double.Parse( cantidadItem.ToString().Substring(0,17));
return double.Parse(cantidadItem.ToString());
}
set { cantidadItem = value; }
}
private string unidadMedida = "";
/// <summary>
/// Indica la unidad de medida en que está expresada la cantidad. En caso que no corresponda, poner N/A.
/// <para>Tipo: ALFA 4</para>
/// </summary>
public string UnidadMedida
{
get
{
//if (unidadMedida.Length > 4)
//{
// return "N/A"; //.Substring(0,4);
//}
//else
//{
return unidadMedida;
//}
}
set { unidadMedida = value; }
}
private string unidadMedidaPDF;
[XmlIgnore]
public string UnidadMedidaPDF
{
get { return unidadMedidaPDF; }
set { unidadMedidaPDF = value; }
}
private double precioUnitarioItem;
/// <summary>
/// Indica la unidad de medida en que está expresada la cantidad.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double PrecioUnitarioItem
{
get
{
if(precioUnitarioItem.ToString().Length > 17)
return Math.Round(double.Parse( precioUnitarioItem.ToString().Substring(0,17)), 2);
return Math.Round(double.Parse(precioUnitarioItem.ToString()), 2);
}
set { precioUnitarioItem = value; }
}
private double precioUnitarioItemFC;
/// <summary>
/// Indica la unidad de medida en que está expresada la cantidad.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double PrecioUnitarioItemFC
{
get
{
if (precioUnitarioItemFC.ToString().Length > 17)
return Math.Round(double.Parse(precioUnitarioItemFC.ToString().Substring(0, 17)), 2);
return Math.Round(double.Parse(precioUnitarioItemFC.ToString()), 2);
}
set { precioUnitarioItemFC = value; }
}
private double precioUnitarioItemPDF;
/// <summary>
/// Indica la unidad de medida en que esta expresada la cantidad
/// </summary>
public double PrecioUnitarioItemPDF
{
get
{
if (precioUnitarioItemPDF.ToString().Length > 17)
{
return Math.Round(double.Parse(precioUnitarioItemPDF.ToString().Substring(0,17)), 2);
}
else
{
return Math.Round(double.Parse(precioUnitarioItemPDF.ToString()), 2);
}
}
set
{
precioUnitarioItemPDF = value;
}
}
private double precioUnitarioItemPDF_FC;
/// <summary>
/// Indica la unidad de medida en que esta expresada la cantidad
/// </summary>
public double PrecioUnitarioItemPDF_FC
{
get
{
if (precioUnitarioItemPDF_FC.ToString().Length > 17)
{
return Math.Round(double.Parse(precioUnitarioItemPDF_FC.ToString().Substring(0, 17)), 2);
}
else
{
return Math.Round(double.Parse(precioUnitarioItemPDF_FC.ToString()), 2);
}
}
set
{
precioUnitarioItemPDF_FC = value;
}
}
private double porcentajeDescuentoItem;
/// <summary>
/// Descuento por ítem en %.
/// <para>Tipo: NUM6</para>
/// </summary>
public double PorcentajeDescuentoItem
{
get
{
if(porcentajeDescuentoItem.ToString().Length > 6)
return double.Parse( porcentajeDescuentoItem.ToString().Substring(0,6));
return double.Parse(porcentajeDescuentoItem.ToString());
}
set { porcentajeDescuentoItem = value; }
}
private double montoDescuentoItem;
/// <summary>
/// Correspondiente al anterior. Totaliza todos los descuentos otorgados al ítem.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double MontoDescuentoItem
{
get
{
if(montoDescuentoItem.ToString().Length > 17)
return double.Parse(montoDescuentoItem.ToString().Substring(0, 17));
return double.Parse(montoDescuentoItem.ToString());
}
set { montoDescuentoItem = value; }
}
private double montoDescuentoItemFC;
/// <summary>
/// Correspondiente al anterior. Totaliza todos los descuentos otorgados al ítem.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double MontoDescuentoItemFC
{
get
{
if (montoDescuentoItemFC.ToString().Length > 17)
return double.Parse(montoDescuentoItemFC.ToString().Substring(0, 17));
return double.Parse(montoDescuentoItemFC.ToString());
}
set { montoDescuentoItemFC = value; }
}
private double porcentajeRecargoItem;
/// <summary>
/// Recargo en % por ítem.
/// <para>Tipo: NUM6</para>
/// </summary>
public double PorcentajeRecargoItem
{
get
{
if(porcentajeRecargoItem.ToString().Length > 6)
return double.Parse( porcentajeRecargoItem.ToString().Substring(0,6));
return double.Parse(porcentajeRecargoItem.ToString());
}
set { porcentajeRecargoItem = value; }
}
private double montoRecargoItem;
/// <summary>
/// Correspondiente al PorcentajeRecargo. Totaliza todos los recargos otorgados al ítem.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double MontoRecargoItem
{
get
{
if(montoRecargoItem.ToString().Length > 17)
return double.Parse( montoRecargoItem.ToString().Substring(0,17));
return double.Parse(montoRecargoItem.ToString());
}
set { montoRecargoItem = value; }
}
private double montoRecargoItemFC;
/// <summary>
/// Correspondiente al PorcentajeRecargo. Totaliza todos los recargos otorgados al ítem.
/// <para>Tipo: NUM 17</para>
/// </summary>
public double MontoRecargoItemFC
{
get
{
if (montoRecargoItemFC.ToString().Length > 17)
return double.Parse(montoRecargoItemFC.ToString().Substring(0, 17));
return double.Parse(montoRecargoItemFC.ToString());
}
set { montoRecargoItemFC = value; }
}
private double montoItemPDF = 0;
public double MontoItemPDF
{
get
{
//if (this.IndicadorFacturacion == ESIndicadorFacturacion.EntregaGratuita)
//{
// montoItem = 0;
//}
//else
//{
montoItemPDF = (CantidadItem * precioUnitarioItemPDF) - MontoDescuentoItem + MontoRecargoItem;
//}
if (montoItemPDF.ToString().Length > 17)
return Math.Round(double.Parse(montoItemPDF.ToString().Substring(0, 17)), 2);
return Math.Round(double.Parse(montoItemPDF.ToString()), 2);
}
set { montoItem = value; }
}
private double montoItemPDF_FC = 0;
public double MontoItemPDF_FC
{
get
{
//if (this.IndicadorFacturacion == ESIndicadorFacturacion.EntregaGratuita)
//{
// montoItem = 0;
//}
//else
//{
montoItemPDF_FC = (precioUnitarioItemPDF_FC * cantidadItem) - MontoDescuentoItemFC + MontoRecargoItemFC;
//}
if (montoItemPDF_FC.ToString().Length > 17)
return Math.Round(double.Parse(montoItemPDF_FC.ToString().Substring(0, 17)), 2);
return Math.Round(double.Parse(montoItemPDF_FC.ToString()), 2);
}
set { montoItemPDF_FC = value; }
}
private double articulosXUnidad = 0;
public double ArticulosXUnidad
{
get { return articulosXUnidad; }
set { articulosXUnidad = value; }
}
private double montoItem = 0;
/// <summary>
/// Valor por línea de detalle. Calcula el valor automaticamente segun la especificacion en la documentacion oficial Formato_CFE_v10 seccion B-24
/// <para>Tipo: NUM 17</para>
/// </summary>
public double MontoItem
{
get
{
//if (this.IndicadorFacturacion == ESIndicadorFacturacion.EntregaGratuita)
//{
// montoItem = 0;
//}
//else
//{
montoItem = (CantidadItem * PrecioUnitarioItem) - MontoDescuentoItem + MontoRecargoItem;
//}
if(montoItem.ToString().Length > 17)
return Math.Round(double.Parse( montoItem.ToString().Substring(0,17)),2);
return Math.Round(double.Parse(montoItem.ToString()), 2);
}
set { montoItem = value; }
}
#endregion DETALLES DE PRODUCTOS
#region CODIGOS DE ITEM
private List<CFEItemsCodigos> itemsCodigos = new List<CFEItemsCodigos>();
/// <summary>
/// Lista de codigos del item
/// </summary>
public List<CFEItemsCodigos> ItemCodigos
{
get { return itemsCodigos; }
set { itemsCodigos = value; }
}
/// <summary>
/// Retorna una nueva instancia de DFEItemsCodigos. A esta instancia se asignan los valores en los campos respectivos y se agrega a la lista
/// mediante el metodo AgregarItemCodigos(CFEItemsCodigos cfeItemCodigos)
/// </summary>
/// <returns></returns>
public CFEItemsCodigos NuevoItemCodigos()
{
return new CFEItemsCodigos();
}
/// <summary>
/// Agrega un nuevo codigo de item a la lista de codigos de items.
/// </summary>
/// <param name="cfeItemCodigos"></param>
public void AgregarItemCodigos(CFEItemsCodigos cfeItemCodigos)
{
if (ItemCodigos.Count < 5)
{
ItemCodigos.Add(cfeItemCodigos);
}
}
#endregion CODIGOS DE ITEM
#region DISTRIBUCION DE DESCUENTO
private List<CFEItemsDistDescuento> itemsDistDescuentos = new List<CFEItemsDistDescuento>();
/// <summary>
/// Lista de distribucion de descuentos
/// </summary>
public List<CFEItemsDistDescuento> ItemsDistDescuentos
{
get { return itemsDistDescuentos; }
set { itemsDistDescuentos = value; }
}
private string tipoImpuesto;
public string TipoImpuesto
{
get { return tipoImpuesto; }
set { tipoImpuesto = value; }
}
/// <summary>
/// Retorna una nueva instancia de CFEItemsDistDescuento. A esta instancia se asignan los valores en los campos respectivos y se agrega a la lista
/// mediante el metodo AgregarItemDistDescuento(CFEItemsDistDescuento cfeItemDistDescuento)
/// </summary>
/// <returns></returns>
public CFEItemsDistDescuento NuevoItemDistDescuento()
{
return new CFEItemsDistDescuento();
}
/// <summary>
/// Agrega un nuevo objeto distribucion de descuento a la lista.
/// </summary>
/// <param name="cfeItemDistDescuento"></param>
public void AgregarItemDistDescuento(CFEItemsDistDescuento cfeItemDistDescuento)
{
if (ItemsDistDescuentos.Count < 5)
{
ItemsDistDescuentos.Add(cfeItemDistDescuento);
}
}
#endregion DISTRIBUCION DE DESCUENTO
#region DISTRIBUCION DE RECARGO
private List<CFEItemsDistRecargo> itemsDistRecargo = new List<CFEItemsDistRecargo>();
/// <summary>
/// Lista de distribucion de regargos
/// </summary>
public List<CFEItemsDistRecargo> ItemsDistRecargos
{
get { return itemsDistRecargo; }
set { itemsDistRecargo = value; }
}
/// <summary>
/// Retorna una nueva instancia de CFEItemsDistRecargo. A esta instancia se asignan los valores en los campos respectivos y se agrega a la lista
/// mediante el metodo AgregarItemDistRecargo(CFEItemsDistRecargo cfeItemDistRecargo)
/// </summary>
/// <returns></returns>
public CFEItemsDistRecargo NuevoItemDistRecargo()
{
return new CFEItemsDistRecargo();
}
/// <summary>
/// Agrega un nuevo objeto distribucion de descuento a la lista.
/// </summary>
/// <param name="cfeItemDistRecargo"></param>
public void AgregarItemDistRecargo(CFEItemsDistRecargo cfeItemDistRecargo)
{
if (ItemsDistRecargos.Count < 5)
{
ItemsDistRecargos.Add(cfeItemDistRecargo);
}
}
#endregion DISTRIBUCION DE RECARGO
#region RETENCION/RECEPCION
private List<CFEItemsRetencPercep> itemsRecepPercep = new List<CFEItemsRetencPercep>();
/// <summary>
/// Lista de recepcion/percepcion
/// </summary>
public List<CFEItemsRetencPercep> ItemsRecepPercep
{
get { return itemsRecepPercep; }
set { itemsRecepPercep = value; }
}
/// <summary>
/// Retorna una nueva instancia de CFEItemsRecepPercep. A esta instancia se asignan los valores en los campos respectivos y se agrega a la lista
/// mediante el metodo AgregarItemRecepPercep(CFEItemsRecepPercep cfeItemsRecepPercep)
/// </summary>
/// <returns></returns>
public CFEItemsRetencPercep NuevoItemsRetencPercep()
{
return new CFEItemsRetencPercep();
}
/// <summary>
/// Agrega un nuevo objeto recepcion/percepcion a la lista.
/// </summary>
/// <param name="cfeItemDistRecargo"></param>
public void AgregarItemRetencPercep(CFEItemsRetencPercep cfeItemsRecepPercep)
{
if (ItemsRecepPercep.Count < 5)
{
ItemsRecepPercep.Add(cfeItemsRecepPercep);
}
}
#endregion RETENCION/RECEPCION
}
}
|
adc0bc0d11ee79153fd8ec7a77a99086dde1641e
|
C#
|
Romazes/TEAM.international-EntityFrameworkCore
|
/Model/Table Per Concrete Class Inheritance/Place.cs
| 2.8125
| 3
|
using System.ComponentModel.DataAnnotations;
namespace Model.Table_Per_Concrete_Class_Inheritance
{
public abstract class Place : BaseEntity
{
[Required(ErrorMessage = "The Name is required.")]
[MaxLength(50)]
public string Name { get; set; }
[Required(ErrorMessage = "The Address is required.")]
[MaxLength(200)]
public string Address { get; set; }
}
}
|
c872d7e2e6785d6ed3424472fa92da597bc904b9
|
C#
|
hvuSyslogic/IronCastle
|
/src/BouncyCastle.PKIX/mime/MimeParserListener.cs
| 2.578125
| 3
|
namespace org.bouncycastle.mime
{
/// <summary>
/// Base interface for a MIME parser listener.
/// </summary>
public interface MimeParserListener
{
/// <summary>
/// Create an appropriate context object for the MIME object represented by headers.
/// </summary>
/// <param name="parserContext"> context object for the current parser. </param>
/// <param name="headers"> MIME headers for the object that has been discovered. </param>
/// <returns> a MimeContext </returns>
MimeContext createContext(MimeParserContext parserContext, Headers headers);
/// <summary>
/// Signal that a MIME object has been discovered.
/// </summary>
/// <param name="parserContext"> context object for the current parser. </param>
/// <param name="headers"> headers for the MIME object. </param>
/// <param name="inputStream"> input stream representing its content. </param>
/// <exception cref="IOException"> in case of a parsing/processing error. </exception>
void @object(MimeParserContext parserContext, Headers headers, InputStream inputStream);
}
}
|
cf899133bba665801f7eb5f500852749d72e1aa1
|
C#
|
ahmed-abdelrazek/BulkExportToModernExcel
|
/ExcelBulkExport/ViewModels/MainWindowViewModel.cs
| 2.703125
| 3
|
using ExcelBulkExport.Core;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
namespace ExcelBulkExport.ViewModels
{
public class MainWindowViewModel : ViewModel
{
private string filesDirectory;
private string extensions;
private string newFilesDirectory;
private int progressBarMaxValue;
private int progressBarCurrentValue;
private bool isError;
private bool isWorking;
public string FilesDirectory
{
get => filesDirectory;
set
{
NotifyPropertyChange(ref filesDirectory, value);
IsError = false;
if (!Directory.Exists(filesDirectory))
{
MessageBox.Show("The Folder you chose doesn't exist", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
IsError = true;
}
}
}
public string Extensions { get => extensions; set => NotifyPropertyChange(ref extensions, value); }
public string NewFilesDirectory
{
get => newFilesDirectory;
set
{
NotifyPropertyChange(ref newFilesDirectory, value);
IsError = false;
if (!Directory.Exists(newFilesDirectory))
{
MessageBox.Show("The Folder you chose doesn't exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
IsError = true;
}
if (!Directory.Exists(newFilesDirectory))
{
MessageBox.Show("Choose a different folder to save to", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}
public int ProgressBarMaxValue { get => progressBarMaxValue; set => NotifyPropertyChange(ref progressBarMaxValue, value); }
public int ProgressBarCurrentValue { get => progressBarCurrentValue; set => NotifyPropertyChange(ref progressBarCurrentValue, value); }
public bool IsError { get => isError; set => NotifyPropertyChange(ref isError, value); }
public bool IsWorking { get => isWorking; set => NotifyPropertyChange(ref isWorking, value); }
public IAsyncCommand ChooseFilesDirectory { get; private set; }
public IAsyncCommand ChooseNewFilesDirectory { get; private set; }
public IAsyncCommand Start { get; private set; }
public IAsyncCommand Stop { get; private set; }
public IAsyncCommand Exit { get; private set; }
public MainWindowViewModel()
{
ProgressBarMaxValue = 100;
Extensions = ".xml, .xls";
ChooseFilesDirectory = new AsyncCommand(DoChooseFilesDirectory);
ChooseNewFilesDirectory = new AsyncCommand(DoChooseNewFilesDirectory);
Start = new AsyncCommand(DoStart, CanStart);
Stop = new AsyncCommand(DoStop, CanStop);
Exit = new AsyncCommand(DoExit, CanExit);
}
private async Task DoChooseFilesDirectory()
{
await Task.Delay(1);
VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog
{
Description = "Please select a folder.",
UseDescriptionForTitle = true // This applies to the Vista style dialog only, not the old dialog.
};
if (dialog.ShowDialog() == true)
{
FilesDirectory = dialog.SelectedPath;
}
}
private async Task DoChooseNewFilesDirectory()
{
await Task.Delay(1);
VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog
{
Description = "Please select a folder.",
UseDescriptionForTitle = true // This applies to the Vista style dialog only, not the old dialog.
};
if (dialog.ShowDialog() == true)
{
NewFilesDirectory = dialog.SelectedPath;
}
}
private bool CanStart()
{
return !IsError;
}
private async Task DoStart()
{
IsWorking = true;
try
{
var di = new DirectoryInfo(FilesDirectory);
var newExts = new List<string>();
foreach (var ext in Extensions.Split(','))
{
newExts.Add(ext.Trim());
}
var AllFiles = di.GetFiles().Where(file => newExts.Any(file.FullName.ToLower().EndsWith)).ToList();
if (AllFiles.Count > 0)
{
progressBarMaxValue = AllFiles.Count;
progressBarCurrentValue = 0;
await Task.Run(() =>
{
foreach (var file in AllFiles)
{
if (!IsWorking)
{
break;
}
var excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook currentWorkbook = excelApp.Workbooks.Open(file.FullName);
currentWorkbook.SaveAs($"{NewFilesDirectory}\\{Path.GetFileNameWithoutExtension(file.FullName)}.xlsx",
Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value,
Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
excelApp.Quit();
progressBarCurrentValue++;
}
});
}
else
{
MessageBox.Show($" There is no {Extensions} Files", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
await DoStop();
}
private bool CanStop()
{
return IsWorking;
}
private async Task DoStop()
{
await Task.Delay(1);
IsWorking = false;
}
private bool CanExit()
{
return true;
}
private async Task DoExit()
{
if (CanStop())
{
await DoStop();
}
System.Environment.Exit(0);
}
}
}
|
6848ccac64002bf22de2c4d94c0a61e9fcf66c4e
|
C#
|
Rabbid76/c_sharp_raytrace_examples
|
/WpfViewModelModule/Utility/RangeLimit.cs
| 3.375
| 3
|
using System;
// [Where can I find the “clamp” function in .NET?](https://stackoverflow.com/questions/2683442/where-can-i-find-the-clamp-function-in-net)
// [How to force a number to be in a range in C#?](https://stackoverflow.com/questions/3176602/how-to-force-a-number-to-be-in-a-range-in-c)
namespace WpfViewModelModule.Utility
{
public class RangeLimit<T> where T : IComparable<T>
{
public T Min { get; }
public T Max { get; }
public RangeLimit(T min, T max)
{
if (min.CompareTo(max) > 0)
throw new InvalidOperationException("invalid range");
Min = min;
Max = max;
}
public void Validate(T param)
{
if (param.CompareTo(Min) < 0 || param.CompareTo(Max) > 0)
throw new InvalidOperationException("invalid argument");
}
public T Clamp(T param) => param.CompareTo(Min) < 0 ? Min : param.CompareTo(Max) > 0 ? Max : param;
}
}
|
e79a1d30e758d66be17f8a95efe76c0de837910c
|
C#
|
Mediocrates10/HumberWork
|
/2D Tank Game/Assets/Scripts/PlayerController.cs
| 2.515625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField]
private float speed = 2f;
[SerializeField]
private float turnSensitivity = 3f;
private PlayerMotor motor;
Vector3 rotation;
void Start()
{
motor = GetComponent<PlayerMotor>();
}
void OnCollisionEnter2D(Collision2D collision)
{
rotation = Vector3.zero;
}
void Update()
{
// Calculate velocity as vector
float yMov = Input.GetAxisRaw("Vertical");
Vector2 verticalMov = transform.up * yMov;
// Final velocity vector
Vector2 velocity = verticalMov.normalized * speed;
// Apply movement
motor.Move(velocity);
// Calculate rotation as vector
float zRot = Input.GetAxisRaw("Rotate");
rotation = new Vector3(0f, 0f, zRot) * turnSensitivity;
// Apply rotation
motor.Rotate(rotation);
}
}
|