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
|
|---|---|---|---|---|---|---|
4b6e3eca1ac3a73c8fa3154c751d5f75359cdb1b
|
C#
|
YendisFish/Panda-Bear
|
/PandaBear/CommonStructureLibrary/SQL/ProtectedDB.cs
| 2.765625
| 3
|
using CSL.Encryption;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace CSL.SQL
{
/// <summary>
/// Uses Sqlite to provide a local Key/Value store and logging functionality.
/// </summary>
public class ProtectedDB :IDisposable
{
private readonly LocalDB innerDB;
private readonly IProtector protector;
/// <summary>
/// Creates a new ProtectedDB at the filepath.
/// </summary>
/// <param name="filepath">The full filepath to create or open the LocalDB.</param>
public ProtectedDB(LocalDB innerDB, IProtector protector)
{
this.innerDB = innerDB;
this.protector = protector;
}
public void Dispose()
{
((IDisposable)innerDB).Dispose();
((IDisposable)protector).Dispose();
}
public async Task<string?> Get(string key)
{
string? toReturn = await innerDB.Get(key);
if (toReturn != null)
{
return await protector.Unprotect(toReturn, key);
}
return null;
}
public async Task Set(string key, string? value)
{
string? toInsert = value;
if (toInsert == null)
{
await innerDB.Set(key, null);
}
else
{
toInsert = await protector.Protect(toInsert, key);
await innerDB.Set(key, toInsert);
}
}
}
}
|
8430929c1a24e480f56476e70a3d4adc82646b27
|
C#
|
shendongnian/download4
|
/code2/362322-7820526-17364086-2.cs
| 2.71875
| 3
|
dt = new DataTable();
dt_Property.Columns.Add("Field1");
int i = 0;
DataRow row = null;
foreach (DataRow r in ds.Tables[0].Rows)
{
row = dt.NewRow();
row["Field1"] = ds.Tables[0].Rows[i][1];
dt_Property.Rows.Add(row);
i = i + 1;
}
dataGridView1.DataSource = dt;
|
f864dcce7f45b15fda3e9e81724f98f78aa5ee43
|
C#
|
macgibbons/Bloom
|
/Bloom/Controllers/V1/BrewMethodsController.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Capstone.Models.Data;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
namespace Capstone.Controllers.V1
{
[Route("api/[controller]")]
[ApiController]
public class BrewMethodsController : ControllerBase
{
private readonly IConfiguration _config;
public BrewMethodsController(IConfiguration config)
{
_config = config;
}
public SqlConnection Connection
{
get
{
return new SqlConnection(_config.GetConnectionString("DefaultConnection"));
}
}
// ----------Get all----------
[HttpGet]
public async Task<IActionResult> Get()
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT *
FROM BrewMethod
WHERE 1 = 1
";
SqlDataReader reader = cmd.ExecuteReader();
List<BrewMethod> allBrewMethods = new List<BrewMethod>();
while (reader.Read())
{
var brewMethod = new BrewMethod()
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
Method = reader.GetString(reader.GetOrdinal("Method")),
PaperFilter = reader.GetBoolean(reader.GetOrdinal("PaperFilter")),
BrewType = reader.GetString(reader.GetOrdinal("BrewType")),
};
if (!reader.IsDBNull(reader.GetOrdinal("ImagePath")))
{
brewMethod.ImagePath = reader.GetString(reader.GetOrdinal("ImagePath"));
}
else
{
brewMethod.ImagePath = null;
}
allBrewMethods.Add(brewMethod);
}
reader.Close();
return Ok(allBrewMethods);
}
}
}
//----------GET by Id----------
[HttpGet("{id}", Name = "GetBrewMethod")]
public async Task<IActionResult> Get([FromRoute] int id)
{
using (SqlConnection conn = Connection)
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"
SELECT *
FROM BrewMethod
WHERE Id = @id";
cmd.Parameters.Add(new SqlParameter("@id", id));
SqlDataReader reader = cmd.ExecuteReader();
BrewMethod brewMethod = null;
if (reader.Read())
{
brewMethod = new BrewMethod()
{
Id = reader.GetInt32(reader.GetOrdinal("Id")),
Method = reader.GetString(reader.GetOrdinal("Method")),
PaperFilter = reader.GetBoolean(reader.GetOrdinal("PaperFilter")),
BrewType = reader.GetString(reader.GetOrdinal("BrewType"))
};
reader.Close();
return Ok(brewMethod);
}
else
{
return NotFound();
}
}
}
}
}
}
|
97179fbf3033236d07e3c7dc04fbbe12b107f5e7
|
C#
|
chenqilscy/LinFx
|
/src/LinFx/Utils/DateTimeUtils.cs
| 3.1875
| 3
|
using System;
namespace LinFx.Utils
{
public static class DateTimeUtils
{
public static object TimeZone { get; private set; }
/// <summary>
/// 得到当前的unix时间戳
/// </summary>
/// <param name="date">当前时间日期</param>
/// <returns></returns>
public static double GetUnixTimestamp(DateTime date)
{
//Int64 result = 0;
//var start = new DateTime(1970, 1, 1, 0, 0, 0, date.Kind);
//result = Convert.ToInt64((date - start).TotalSeconds);
//return result;
//double intResult = 0;
//DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
//intResult = (date - startTime).TotalSeconds;
//return intResult;
return date.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
}
public static long ToUnixTimeSeconds(this DateTime dt)
{
return new DateTimeOffset(dt).ToUnixTimeSeconds();
}
}
}
|
9a19c166bc56752a8d31ac9992e689f9f9b4e879
|
C#
|
zrobi0621/reversi
|
/Reversi/SQLiteDataAccess.cs
| 2.78125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SQLite;
using System.Configuration;
using Dapper;
namespace Reversi
{
class SQLiteDataAccess
{
private static string LoadConnectionString(string id = "Default")
{
return ConfigurationManager.ConnectionStrings[id].ConnectionString;
}
//LOAD
public static List<Highscore> LoadHighscores()
{
using (IDbConnection connection = new SQLiteConnection(LoadConnectionString()))
{
var output = connection.Query<Highscore>("SELECT * FROM Highscores", new DynamicParameters());
return output.ToList();
}
}
//INSERT
public static void AddHighscore(Highscore highscore)
{
using (IDbConnection connection = new SQLiteConnection(LoadConnectionString()))
{
connection.Execute("INSERT INTO Highscores (WhitePlayer, BlackPlayer, Time, WhitePoints, BlackPoints, Date) VALUES (@WhitePlayer, @BlackPlayer, @Time, @WhitePoints, @BlackPoints, @Date)", highscore);
}
}
//DELETE
public static void DeleteHighscores()
{
using (IDbConnection connection = new SQLiteConnection(LoadConnectionString()))
{
connection.Execute("DELETE FROM Highscores");
connection.Execute("VACUUM");
}
}
}
}
|
5c2b771875e7232c38938612f2ec14f496025cc8
|
C#
|
dillonmrose/Utilities
|
/Tools/Tools/MachineLearning/LearningModelFactory.cs
| 2.6875
| 3
|
#include "pch.h"
using namespace std;
unordered_map <wstring, LearningModelType> LearningModelFactory::modelNameToType =
{
{L"LinearModel", LearningModelType::LinearModelType },
{L"DecisionTree", LearningModelType::DecisionTreeType },
{L"LearningModelEnsemble", LearningModelType::LearningModelEnsembleType }
};
shared_ptr<LearningModel> LearningModelFactory::CreateLearningModel(LearningModelType modelType)
{
switch (modelType)
{
case LinearModelType:
return make_shared <LinearModel>();
case DecisionTreeType:
return make_shared <DecisionTree>();
case LearningModelEnsembleType:
return make_shared <LearningModelEnsemble>();
default:
return make_shared <LearningModel>();
}
}
shared_ptr<LearningModel> LearningModelFactory::CreateLearningModel(const wstring& modelName)
{
return CreateLearningModel(modelNameToType[modelName]);
}
shared_ptr<LearningModel> LearningModelFactory::CreateLearningModelFromTextFile(wistream& textFile)
{
wstring name;
textFile >> name;
shared_ptr<LearningModel> model = CreateLearningModel(name);
model->Initialize(textFile);
return model;
}
shared_ptr<LearningModel> LearningModelFactory::CreateLearningModelFromBinaryFile(vector<char>& binaryFile)
{
size_t pos = 0;
return CreateLearningModelFromBinaryFile(binaryFile, pos);
}
shared_ptr<LearningModel> LearningModelFactory::CreateLearningModelFromBinaryFile(vector <char>& binaryFile, size_t& pos)
{
LearningModelType type = static_cast<LearningModelType>(binaryFile[pos]);
++pos;
shared_ptr<LearningModel> model = CreateLearningModel(type);
model->Initialize(binaryFile, pos);
return model;
}
|
6187a23ffc3ef3d262c3d09d18b323ea9191ae9b
|
C#
|
prasad1261997/swabhav-techlabs
|
/C#/OOP/Exception-App/Exception-App/Account.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Exception_App
{
class Account
{
private readonly int accountNumber;
private readonly string name;
private double balance;
private static int count;
private const double Minimum_Balance = 500;
public Account(int a, String n, double b)
{
this.accountNumber = a;
this.name = n;
this.balance = b;
count += 1;
Console.WriteLine("Inside the constructor block");
}
static Account()
{
count = 100;
Console.WriteLine("Inside the Static block");
}
public Account(int a, String n)
: this(a, n, 500.0)
{
}
public void deposit(double amt)
{
balance = balance + amt;
}
public void withdraw(double amt)
{
if (balance - amt > Minimum_Balance)
{
balance = balance - amt;
}
else
{
throw new InsufficientFundException(this, amt);
}
}
public int AccountNO
{
get
{
return accountNumber;
}
}
public string Name
{
get
{
return name;
}
}
public double Balance
{
get
{
return balance;
}
}
public int Count
{
get
{ return count; }
}
public static int HeadCount
{
get
{
return count;
}
}
}
}
|
e4214ba4e3adb3a62ce02b12e294612c54429f6d
|
C#
|
WojciechKrawczyk/TravelAgency
|
/Project1/Decorator.cs
| 2.828125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;
// Potwierdzam samodzielność powyższej pracy oraz niekorzystanie przeze mnie z niedozwolonych źródeł
// <Wojciech> <Krawczyk>
namespace TravelAgencies.DataAccess
{
interface EncryptedData
{
string GetData();
}
class EncryptedNumber : EncryptedData
{
string data;
public EncryptedNumber(string number)
{
this.data = number;
}
public string GetData()
{
return this.data;
}
}
abstract class EncryptedDataDecorator: EncryptedData
{
protected EncryptedData data;
public EncryptedDataDecorator(EncryptedData data)
{
this.data = data;
}
public virtual string GetData()
{
return data.GetData();
}
}
class FrameCodecDecorator: EncryptedDataDecorator
{
private int n;
public FrameCodecDecorator(EncryptedData data, int n):base(data)
{
this.n = n;
}
public override string GetData()
{
if (n < 0 || n > 9)
throw new ArgumentException();
StringBuilder main = new StringBuilder();
StringBuilder sb = new StringBuilder();
StringBuilder rsb = new StringBuilder();
for (int i = 1; i <= this.n; i++)
{
sb.Append(i.ToString());
rsb.Insert(0, i.ToString());
}
main.Append(sb).Append(this.data.GetData()).Append(rsb);
return main.ToString();
}
}
class FrameDecodecDecorator: EncryptedDataDecorator
{
private int n;
public FrameDecodecDecorator(EncryptedData data, int n) : base(data)
{
this.n = n;
}
public override string GetData()
{
if (n < 0 || n > 9)
throw new ArgumentException();
char[] tab = base.GetData().ToCharArray();
if (2 * this.n >= tab.Length)
return string.Empty;
StringBuilder sb = new StringBuilder();
for (int i = n; i < tab.Length-n; i++)
{
sb.Append(tab[i]);
}
return sb.ToString();
}
}
class ReverseCodecDecorator: EncryptedDataDecorator
{
public ReverseCodecDecorator(EncryptedData data) : base(data) { }
public override string GetData()
{
char[] tab = base.GetData().ToCharArray();
Array.Reverse(tab);
return new string(tab);
}
}
class PushCodecDecorator: EncryptedDataDecorator
{
private int n;
public PushCodecDecorator(EncryptedData data, int n) : base(data)
{
this.n = n;
}
public override string GetData()
{
string s = base.GetData();
if (this.n == 0 || s.Length < 1)
return s;
char[] tab = s.ToCharArray();
char outc;
if (n > 0)
{
for (int i = 1; i <= n; i++)
{
char inc = tab[0];
for (int j = 1; j < s.Length; j++)
{
outc = tab[j];
tab[j] = inc;
inc = outc;
}
tab[0] = inc;
}
return new string(tab);
}
if (n < 0)
{
for (int i = 1; i <= Math.Abs(n); i++)
{
char inc = tab[tab.Length - 1];
for (int j = tab.Length - 2; j >= 0; j--)
{
outc = tab[j];
tab[j] = inc;
inc = outc;
}
tab[tab.Length - 1] = inc;
}
}
return new string(tab);
}
}
class CezarCodecDecorator: EncryptedDataDecorator
{
private int n;
public CezarCodecDecorator(EncryptedData data, int n) : base(data)
{
this.n = n;
}
public override string GetData()
{
int j = this.n % 10;
char[] tab = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] ret = base.GetData().ToCharArray();
for (int i = 0; i < ret.Length; i++)
{
int k = (ret[i] - 48 + j) % 10;
if (k < 0)
k = k + 10;
ret[i] = tab[k];
}
return new string(ret);
}
}
class SwapCodecDecorator: EncryptedDataDecorator
{
public SwapCodecDecorator(EncryptedData data) : base(data) { }
public override string GetData()
{
char[] tab = base.GetData().ToCharArray();
int l = tab.Length % 2;
for (int i = 0; i <= tab.Length - 2 - l; i += 2)
{
char p = tab[i];
tab[i] = tab[i + 1];
tab[i + 1] = p;
}
return new string(tab);
}
}
//Special DecodecMachine used by TravelAgencies
class BookingDecodec
{
public int GetRealNumber(EncryptedData data)
{
SwapCodecDecorator swap = new SwapCodecDecorator(data);
CezarCodecDecorator cezar = new CezarCodecDecorator(swap, 1);
ReverseCodecDecorator reverse = new ReverseCodecDecorator(cezar);
FrameDecodecDecorator fd = new FrameDecodecDecorator(reverse, 2);
return int.Parse(fd.GetData());
}
}
class TripAdvisorDecodec
{
public int GetRealNumber(EncryptedData data)
{
PushCodecDecorator push = new PushCodecDecorator(data, -3);
SwapCodecDecorator swap = new SwapCodecDecorator(push);
FrameDecodecDecorator fd = new FrameDecodecDecorator(swap, 2);
push = new PushCodecDecorator(fd, -3);
return int.Parse(push.GetData());
}
}
class ShutterStockDecodec
{
public int GetRealNumber(EncryptedData data)
{
ReverseCodecDecorator reverse = new ReverseCodecDecorator(data);
PushCodecDecorator push = new PushCodecDecorator(reverse, 3);
FrameDecodecDecorator fd = new FrameDecodecDecorator(push, 1);
CezarCodecDecorator cezar = new CezarCodecDecorator(fd, -4);
return int.Parse(cezar.GetData());
}
}
}
|
be0076a20241e994d6e735ee34a51de234b3c227
|
C#
|
HTW-Berlin-CAVE/cave-package
|
/CaveSampleProject/Packages/de.htw.cave/ThirdParty/KalmanFilterSimple1D/KalmanFilterSimple1D.cs
| 2.875
| 3
|
using System;
// based on http://habrahabr.ru/post/140274/
// this is a slightly modified version
namespace KalmanFilterSimple
{
public class KalmanFilterSimple1D
{
public double X0 { get; private set; } // predicted state
public double P0 { get; private set; } // predicted covariance
public double F { get; private set; } // factor of real value to previous real value
public double Q { get; private set; } // measurement noise
public double H { get; private set; } // factor of measured value to real value
public double R { get; private set; } // environment noise
public double State { get; private set; }
public double Covariance { get; private set; }
public KalmanFilterSimple1D(double q, double r, double f = 1, double h = 1)
{
this.Q = q;
this.R = r;
this.F = f;
this.H = h;
}
public void SetState(double state, double covariance)
{
this.State = state;
this.Covariance = covariance;
}
public void Correct(double data)
{
//time update - prediction
this.X0 = this.F * State;
this.P0 = this.F * Covariance * this.F + this.Q;
//measurement update - correction
double k = this.H * this.P0 / (this.H * this.P0 * this.H + this.R);
this.State = this.X0 + k * (data - this.H * this.X0);
this.Covariance = (1 - k * this.H) * this.P0;
}
}
}
|
519a8b47519a568d25cf051fdccdf53b9de4e8dd
|
C#
|
JTLaMarre/JavaBox
|
/GameAPI/Storage/GameContext.cs
| 2.71875
| 3
|
using GameAPI.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace GameAPI.Storage
{
public class GameContext:DbContext
{
public DbSet<Game> Game{get;set;}
public DbSet<GamePrompts> GamePrompt{get;set;}
public DbSet<Prompt> Prompt{get;set;}
GameContext(){}
public GameContext(DbContextOptions<GameContext> options) : base(options) { }
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseSqlServer("SqlServer");
}
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Game>().HasKey(x => x.EntityId);
builder.Entity<GamePrompts>().HasKey(x => x.EntityId);
builder.Entity<Prompt>().HasKey(x => x.EntityId);
}
}
}
|
b798db7aff539aad6942cf2b8932ef2d27edb3e5
|
C#
|
attackgithub/SharpDevelopCodeCompletion
|
/ICSharpCode.AvalonEdit.CodeCompletion/Indexers/IndexerInsightProvider.cs
| 2.6875
| 3
|
using System.Linq;
using ICSharpCode.SharpDevelop.Dom;
namespace ICSharpCode.AvalonEdit.CodeCompletion.Indexers
{
/// <summary>
/// Produces MethodInsightItem instances for showing the insight window on indexer calls.
/// </summary>
public class IndexerInsightProvider : MethodInsightProvider
{
public IndexerInsightProvider(IProjectContent projectContent) : base(projectContent)
{
}
public override IInsightItem[] ProvideInsight(ExpressionResult expressionResult, ResolveResult result)
{
if (result == null)
return null;
var type = result.ResolvedType;
if (type == null)
return null;
var indexers = type.GetProperties()
.Where(property => property.IsIndexer)
.ToArray();
if (indexers.Any(property => property.Parameters.Any(parameter => parameter.ReturnType == null)))
{
return indexers
.Select(indexer => new MethodInsightItem(indexer))
.Cast<IInsightItem>()
.ToArray();
}
var groupedIndexers = indexers.GroupBy(property => property.Parameters.GetKey());
var insightItems = groupedIndexers
.Select(
grouping =>
grouping.OrderByDescending(property => property.DeclaringType, new ClassComparer()).First())
.Select(property => new MethodInsightItem(property))
.Cast<IInsightItem>()
.ToArray();
return insightItems;
}
}
} ;
|
8c4dbbeabcf1032c48cbfd6eb4df11b88d419d2b
|
C#
|
Kalishir/GDLCreatureBreeder
|
/Assets/Scripts/DataModel/CreatureManager.cs
| 3.03125
| 3
|
using UnityEngine;
using System.IO;
using System.Collections.Generic;
public class CreatureManager : MonoBehaviour, System.IDisposable
{
/*
ISSUE: Dictionaries are not serializable in the Unity Editor.
TODO:
Either
1) Ham this with some basic code that grabs two lists for Keys and Values in the manager
2) Create a script that allows for full serialization of a Dictionary (which would be kind of the same, but a bit more work).
Third party options:
There are a few open source versions available once the legal stuff is sorted such as Vexe's Framework (VXF)
There are also purchased assets available that do the same such as Advanced Inspector.
*/
private Dictionary<CreatureType, List<CreatureData>> creaturesDictionary;
// Singleton Enforcement
static private CreatureManager manager;
static public CreatureManager Manager
{
get
{
return manager;
}
private set
{
manager = value;
}
}
private bool disposed;
public void Awake()
{
if (manager == null)
{
Manager = this;
DontDestroyOnLoad(gameObject);
SetupDictionary(creaturesDictionary);
//Load Creatures from JSON
LoadCreatureLibrary(creaturesDictionary);
}
else if (manager != this)
{
Destroy(this);
}
}
public void Start()
{
}
private void SetupDictionary(Dictionary<CreatureType, List<CreatureData>> dictionary)
{
dictionary = new Dictionary<CreatureType, List<CreatureData>>();
var creatureTypes = System.Enum.GetValues(typeof(CreatureType)) as CreatureType[];
foreach (var creatureType in creatureTypes)
{
dictionary.Add( creatureType, new List<CreatureData>() );
}
creaturesDictionary = dictionary;
}
private void LoadCreatureLibrary(Dictionary<CreatureType, List<CreatureData>> dictionary)
{
if (dictionary == null)
return;
string path = "CreatureData/";
foreach (var creatureName in System.Enum.GetNames(typeof(CreatureType)))
{
if (creatureName == "Invalid")
continue;
var fileContents = Resources.Load<TextAsset>(path + creatureName + "/info").text;
var creatureNames = fileContents.Split(' ');
foreach (var name in creatureNames)
{
CreatureData creature = JsonUtility.FromJson<CreatureData>(Resources.Load<TextAsset>(path + creatureName + "/" + name).text);
dictionary[creature.Type].Add(creature);
}
}
/*
var info = new DirectoryInfo("Assets/Resources/" + path);
var folders = info.GetDirectories();
foreach (var folder in folders)
{
string subFolderPath = path + folder.Name;
var subFolderInfo = new DirectoryInfo("Assets/Resources/" + subFolderPath);
var files = subFolderInfo.GetFiles("*.JSON");
foreach (var file in files)
{
string fileName = "/" + file.Name.Split('.')[0];
CreatureData creature = JsonUtility.FromJson<CreatureData>(Resources.Load<TextAsset>(subFolderPath + fileName).text);
dictionary[creature.Type].Add(creature);
}
}
*/
creaturesDictionary = dictionary;
}
/// <summary>
/// Gets a random creature's data loaded from JSON.
/// </summary>
/// <returns>A CreatureData object of a random type</returns>
public CreatureData GetRandomCreature()
{
//selects which type the resultant creature will be
var values = System.Enum.GetValues(typeof(CreatureType));
CreatureType creatureType = (CreatureType)values.GetValue(Random.Range(1, values.Length));
return GetCreatureOfType(creatureType);
}
/// <summary>
/// Gets a random Creature's data loaded from JSON on start matching the type supplied as a parameter.
/// </summary>
/// <param name="creatureType">The Type of the creature to find</param>
/// <returns>A CreatureData object with a type matching that requested</returns>
public CreatureData GetCreatureOfType(CreatureType creatureType)
{
//selects the specific creature from the type list
int creatureLocation = Random.Range(0, creaturesDictionary[creatureType].Count);
return creaturesDictionary[creatureType][creatureLocation];
}
/// <summary>
/// Gets a specific creature's data from the JSON loaded on start
/// </summary>
/// <param name="type">The type of the creature to find</param>
/// <param name="name">The name of the creature to find, not case sensitive</param>
/// <returns>The Specific Creature if it exists. Throws an Exception if the creature is not in the dictionary</returns>
public CreatureData GetSpecificCreature(CreatureType type, string name)
{
foreach (var creature in creaturesDictionary[type])
{
if (creature.Name.ToLower() == name.ToLower())
return creature;
}
throw new System.Exception("Creature Not In Dictionary");
}
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
void OnDestroy()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if(disposed)
{
return;
}
if(disposing)
{
// Nothing managed needs to be disposed.
}
foreach(var kvp in creaturesDictionary)
{
kvp.Value.Clear();
}
creaturesDictionary.Clear();
creaturesDictionary = null;
Manager = null;
disposed = true;
}
}
|
f11fc7502f49347241ff0003ca93315e7725a7fa
|
C#
|
hillwah/ODK-DarkEmu
|
/GameServer/GameLSClient.cs
| 2.671875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Diagnostics;
using Core;
using Database;
using System.Net;
namespace GameServer
{
public class GameLSClient
{
public NetworkStream netstream;
public GameLSClient(TcpClient client)
{
GameServer.LoginServer = this;
netstream = client.GetStream();
byte[] message = new byte[4096];
int msgsize = 0;
while (true)
{
try { msgsize = netstream.Read(message, 0, 4096); }
catch { break; } //socket error
if (msgsize == 0)
{
break; // lost connection to login server
}
//message received
HandlePacket(message.Take(msgsize).ToArray());
}
GConsole.WriteError("Lost connection to loginserver.");
client.Close();
}
public void HandlePacket(byte[] packet)
{
ushort id = BitConverter.ToUInt16(packet.Take(2).ToArray(), 0);
switch ((PacketID)id)
{
case PacketID.LGIncomingConnection:
IncomingConnection(new LGIncomingConnection(packet));
break;
}
}
public void IncomingConnection(LGIncomingConnection packet)
{
GameServer.AuthPlayers.Add(packet.AuthKey, packet.UserID);
GConsole.WriteStatus("Received LGIncomingConnection: {0}:{1}:{2}", packet.UserID, packet.PCName, packet.AuthKey);
}
}
}
|
e40cb5099850cc00e37cf5217b44805d7cd6fab6
|
C#
|
shendongnian/download4
|
/code8/1501791-41293451-134456971-4.cs
| 3.265625
| 3
|
int[,] test = new int[4, 3]
{
{45, 23, 9},
{3, -4, -134},
{67, 53, 32},
{0, 1, 0}
};
// test.GetLength(n) will give the length at nth dimension.
// test.Length will give total length. (4*3)
var colLength = test.GetLength(1);
for (int i = 0; i < test.Length - 1; i++)
{
for (int j = i + 1; j < test.Length; j++)
{
int row1, col1; // for first item
int row2, col2; // next item
Get2DIndex(i, colLength, out row1, out col1); // calculate indexes for first item
Get2DIndex(j, colLength, out row2, out col2); // calculate indexes for next item
if (test[col2, row2] < test[col1, row1]) // simple swap
{
var temp = test[col2, row2];
test[col2, row2] = test[col1, row1];
test[col1, row1] = temp;
}
}
}
for (int i = 0; i < test.GetLength(0); i++)
{
for (int j = 0; j < test.GetLength(1); j++)
{
Console.Write("{0}\t", test[i, j]);
}
Console.WriteLine();
}
|
8e0836f8a16e5773a298944f55caeccf27137a43
|
C#
|
SchmobertRitz/SoftwareCityVirtualReality
|
/Assets/Utils/AnimateThis/FloatModel.cs
| 2.8125
| 3
|
using UnityEngine;
using System.Collections;
public class FloatModel : MonoBehaviour {
public string name;
[SerializeField]
private float value;
public delegate void OnFloatModelValueChanged(FloatModel model);
public OnFloatModelValueChanged onFloatModelValueChangedHandler;
public void SetValue(float value)
{
this.value = Mathf.Max(0, Mathf.Min(1, value));
onFloatModelValueChangedHandler(this);
}
public float GetValue()
{
return value;
}
}
|
5b18af621c7d1e9cb8bed167e2d350db819192d0
|
C#
|
StefanSinapov/TelerikAcademy
|
/11. Databases and SQL/15. Processing XML in .NET/13. XSLT Transformation/XslTransformation.cs
| 3.296875
| 3
|
/*
* 13. Write a C# program to apply the XSLT
* stylesheet transformation on the file
* catalog.xml using the class XslTransform.
*/
namespace _13.XSLT_Transformation
{
using System;
using System.Xml.Xsl;
class XslTransformation
{
private const string XmlFilePath = "../../../01. XML File/catalog.xml";
private const string XslFilePath = "../../../12. XSLT File/catalog.xslt";
private const string OutputFilePath = "../../../output/catalog.html";
static void Main()
{
try
{
var xslt = new XslCompiledTransform();
xslt.Load(XslFilePath);
xslt.Transform(XmlFilePath, OutputFilePath);
Console.WriteLine("File successfully created at {0}", OutputFilePath);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
|
dd035096aa99da4ca024a6bfafa99b28e6e79586
|
C#
|
sandeepmvn/classprojectMVC
|
/Desktop/WebApplication2/WebApplication2/CustomModelBinder/CustomEmployeeBinder.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Models;
namespace WebApplication2
{
public class CustomEmployeeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Employee employee;
if (bindingContext.Model == null)
{
employee = new Employee();
employee.OffAddress = new Address();
employee.ResAddress = new Address();
}
else
{
employee = (Employee)bindingContext.Model;
}
employee.Name = GetValue<string>(bindingContext, "Name");
//employee.Age = GetValue<int>(bindingContext, "Age");
employee.OffAddress.Street = GetValue<string>(bindingContext, "OffAddressStreet");
employee.OffAddress.City = GetValue<string>(bindingContext, "OffAddressCity");
employee.ResAddress.Street=GetValue<string>(bindingContext, "ResAddressStreet");
employee.ResAddress.City = GetValue<string>(bindingContext, "ResAddressCity");
return employee;
}
private T GetValue<T>(ModelBindingContext bindingContext, string key)
{
//At runtime the MVC framework populates the ValueProvider with values it finds in the request’s form, route, and query string collections.
ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(key);
bindingContext.ModelState.SetModelValue(key, valueResult); //**
return (T)valueResult.ConvertTo(typeof(T));
}
}
}
|
3e7d3d6596a3e65f65968907a80fb0272c9c5535
|
C#
|
mathlander/CsMathematics
|
/LinearAlgebra/IReadOnlyVector.cs
| 3.390625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CsMathematics.LinearAlgebra
{
public interface IReadOnlyVector : IEquatable<IVector>, IEquatable<IReadOnlyVector>, IEnumerable<double>
{
/// <summary>
/// Returns the number of elements in the vector.
/// </summary>
int Length { get; }
/// <summary>
/// Gets the vector value at the specified index. Valid values are 1 through Length.
/// </summary>
/// <param name="index">The index of the element which should be returned.</param>
/// <returns>The value at the specified vector index.</returns>
double this[int index] { get; }
/// <summary>
/// Performs the binary operation of vector addition.
/// </summary>
/// <param name="vector">The vector whose values should be added to those of the current instance.</param>
/// <returns>A new IReadOnlyVector instance resulting from the addition of the current vector to the input vector.</returns>
IReadOnlyVector Add(IVector vector);
/// <summary>
/// Performs the binary operation of vector addition.
/// </summary>
/// <param name="vector">The vector whose values should be added to those of the current instance.</param>
/// <returns>A new IReadOnlyVector instance resulting from the addition of the current vector to the input vector.</returns>
IReadOnlyVector Add(IReadOnlyVector vector);
/// <summary>
/// Performs the binary operation of vector subtraction.
/// </summary>
/// <param name="vector">The vector whose values should be subtracted from those of the current instance.</param>
/// <returns>A new IReadOnlyVector instance resulting from the subtraction of the input vector from the current vector.</returns>
IReadOnlyVector Subtract(IVector vector);
/// <summary>
/// Performs the binary operation of vector subtraction.
/// </summary>
/// <param name="vector">The vector whose values should be subtracted from those of the current instance.</param>
/// <returns>A new IReadOnlyVector instance resulting from the subtraction of the input vector from the current vector.</returns>
IReadOnlyVector Subtract(IReadOnlyVector vector);
/// <summary>
/// Performs the binary operation of an inner product.
/// </summary>
/// <param name="vector">The second input to the inner product.</param>
/// <returns>The value resulting from the inner product.</returns>
double InnerProduct(IVector vector);
/// <summary>
/// Performs the binary operation of an inner product.
/// </summary>
/// <param name="vector">The second input to the inner product.</param>
/// <returns>The value resulting from the inner product.</returns>
double InnerProduct(IReadOnlyVector vector);
/// <summary>
/// Performs multiplication on the current vector and the input vector as that of an mx1 matrix multiplied with a 1xn matrix.
/// </summary>
/// <param name="vector">A vector which will act as a 1xn matrix for the purposes of matrix multiplication.</param>
/// <returns>A new IReadOnlyMatrix instance which results from matrix multiplication of a column vector with a row vector.</returns>
IReadOnlyMatrix OuterProduct(IVector vector);
/// <summary>
/// Performs multiplication on the current vector and the input vector as that of an mx1 matrix multiplied with a 1xn matrix.
/// </summary>
/// <param name="vector">A vector which will act as a 1xn matrix for the purposes of matrix multiplication.</param>
/// <returns>A new IReadOnlyMatrix instance which results from matrix multiplication of a column vector with a row vector.</returns>
IReadOnlyMatrix OuterProduct(IReadOnlyVector vector);
/// <summary>
/// Multiplies every element of the vector by the scalar parameter.
/// </summary>
/// <param name="scalar">The scaling factor for the vector.</param>
/// <returns>A new IReadOnlyVector instance parallel to the current instance and scaled by the 'scalar' factor.</returns>
IReadOnlyVector MultiplyByScalar(double scalar);
}
}
|
b6b8ef874999391ddf95cb71714e5c32aa429661
|
C#
|
andrew-paes/Auge
|
/Auge/Auge.Repository/Models/Mapping/EnderecoMap.cs
| 2.65625
| 3
|
using Auge.Model.Entities;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Auge.Repository.Models.Mapping
{
public class EnderecoMap : EntityTypeConfiguration<Endereco>
{
public EnderecoMap()
{
// Primary Key
this.HasKey(t => t.EnderecoId);
// Properties
this.Property(t => t.Bairro)
.HasMaxLength(50);
this.Property(t => t.Cep)
.HasMaxLength(10);
this.Property(t => t.Cidade)
.HasMaxLength(50);
this.Property(t => t.Estado)
.HasMaxLength(30);
this.Property(t => t.Numero)
.HasMaxLength(10);
this.Property(t => t.Rua)
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("Endereco");
this.Property(t => t.EnderecoId).HasColumnName("EnderecoId");
this.Property(t => t.PessoaId).HasColumnName("PessoaId");
this.Property(t => t.Bairro).HasColumnName("Bairro");
this.Property(t => t.Cep).HasColumnName("Cep");
this.Property(t => t.Cidade).HasColumnName("Cidade");
this.Property(t => t.Estado).HasColumnName("Estado");
this.Property(t => t.Numero).HasColumnName("Numero");
this.Property(t => t.Rua).HasColumnName("Rua");
// Relationships
this.HasRequired(t => t.Pessoa)
.WithMany(t => t.Enderecos)
.HasForeignKey(d => d.PessoaId);
}
}
}
|
92c54bc6b7d7404f0861c79efffef423e661074f
|
C#
|
halyhuang1991/Tools
|
/Csharp/Mess/MyIEnumerable.cs
| 3.484375
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
namespace Csharp.Mess
{
class Enumeratable1<T> : IEnumerable<T> {
private T[] t;
public string this[int index]
{
get { return this[index]; }
set { this[index] = value; }
}
public Enumeratable1(T[] a) {
t = new T[a.Length];
for (int i = 0; i < t.Length; i++) { t[i] = a[i]; } }
public IEnumerator<T> GetEnumerator() {
for (int i = 0; i <t.Length; i++)
{
yield return t[i];
}
//return new Enumerator1<T>(t);
}
IEnumerator IEnumerable.GetEnumerator() {
for (int i = 0; i <t.Length; i++)
{
yield return t[i];
}
//return new Enumerator1<T>(t);
}
}
public class MyIEnumerable:IEnumerable
{
private string[] arr=new string[1024];
private int len=0;
public string this[int index]
{
get { return arr[index]; }
set { arr[index] = value; }
}
public void Add(string s)
{
if (len==arr.Length)
{
string[] oldArr = arr;
arr = new string[oldArr.Length*2];
oldArr.CopyTo(arr, 0);
}
arr[len]=s;
len++;
Console.WriteLine("add "+s);
}
public IEnumerable<string> BottomToTop {
get { for (int i = 0; i < len; i++) { yield return arr[i]; } }
}
public IEnumerable<string> TopToBottom {
get { for (int i = len-1; i >=0; i--) { yield return arr[i]; } }
}
// IEnumerator IEnumerable.GetEnumerator()
// {
// for (int i = 0; i < arr.Length; i++)
// {
// yield return arr[i];
// }
// }
public string Current
{
get
{
if (len == -1)
{
throw new InvalidOperationException();
}
return arr[len];
}
}
public IEnumerator GetEnumerator()
{
try
{
for (int i = 0; i <len; i++)
{
yield return arr[i];
}
}
finally
{
Console.WriteLine("停止迭代!");
}
//throw new NotImplementedException();
}
}
}
|
750f78b7bbeb70bf1c9df3ed12174f26fdd24ed2
|
C#
|
qdfly/ZHYD4
|
/src/SFBR.Device.Api/Application/Queries/RegionQueries.cs
| 2.5625
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Dapper;
namespace SFBR.Device.Api.Application.Queries
{
public class RegionQueries : IRegionQueries, IDisposable
{
private readonly IDbConnection _connection;
public RegionQueries(IDbConnection connection)
{
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
if (_connection.State == ConnectionState.Closed) _connection.Open();
}
public async Task<List<RegionModel>> GetChildren(string id)
{
string sqltext = "SELECT * FROM Regions WHERE ParentId=@id";
var children = await _connection.QueryAsync<RegionModel>(sqltext, new { id });
return children.ToList();
}
public async Task<RegionModel> GetParent(string id)
{
string sqltext = "SELECT * FROM Regions WHERE Id=@id";
var parent = await _connection.QueryFirstAsync<RegionModel>(sqltext, new { id });
return parent;
}
public async Task<List<RegionModel>> GetRegionList()
{
string sqltext = "SELECT * FROM Regions";
var regions = await _connection.QueryAsync<RegionModel>(sqltext);
return regions.ToList();
}
public async Task<List<TerminalDevice>> GetTerminals(string id)
{
string sqltext = "SELECT * FROM Regions Devices WHERE RegionId=@Id";
var result = await _connection.QueryAsync<TerminalDevice>(sqltext,new { Id=id});
return result.ToList();
}
#region GetTree
public async Task<List<RegionTreeModel>> GetTree()
{
List<RegionTreeModel> result = GetRoots();
foreach (var item in result)
{
CreateTheTree(item.Id, item);
}
return await Task.FromResult(result);
}
public void CreateTheTree(string parentId, RegionTreeModel model)
{
string sqltext = "SELECT * FROM Regions WHERE ParentId=@parentId";
var childern = _connection.Query<RegionTreeModel>(sqltext, new { parentId = parentId }).ToList();
if (childern.Count == 0) return;
foreach (var item in childern)
{
model.Children = childern;
CreateTheTree(item.Id, item);
}
}
public List<RegionTreeModel> GetRoots()
{
string sqltext = "SELECT * FROM Regions WHERE ParentId IS NULL OR ParentId=' '";
var roots = _connection.Query<RegionTreeModel>(sqltext).ToList();
return roots;
}
#endregion
#region 垃圾回收(回收链接)
private bool disposed = false;
public void Dispose()
{
Dispose(true);
//通知垃圾回收机制不再调用终结器(析构器)
GC.SuppressFinalize(this);
}
~RegionQueries()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
// 清理托管资源
_connection.Dispose();
}
//让类型知道自己已经被释放
disposed = true;
}
#endregion
}
}
|
17138cee10f80dd760b1d0cf1d604b283aa143f4
|
C#
|
Gurupadagiri/Benaa2018
|
/Benaa2018.Data.Helpers/TagMasterHelper.cs
| 2.671875
| 3
|
using Benaa2018.Data.Interfaces;
using Benaa2018.Data.Model;
using Benaa2018.Helper.Interface;
using Benaa2018.Helper.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Benaa2018.Helper
{
public class TagMasterHelper : ITagMasterHelper
{
private readonly ITagMasterRepository _tagMasterHelper;
public TagMasterHelper(ITagMasterRepository tagMasterRepository)
{
_tagMasterHelper = tagMasterRepository;
}
public async Task<List<TagMasterViewModel>> GetAllTagMasterDetails(int TagsId = 0)
{
List<TagMasterViewModel> lstTagMasterModel = new List<TagMasterViewModel>();
var tagInfo = await _tagMasterHelper.GetAllAsync();
tagInfo.ToList().ForEach(item =>
{
lstTagMasterModel.Add(new TagMasterViewModel
{
TagId=item.TagId,
TagName=item.TagName
});
});
if(TagsId > 0)
{
lstTagMasterModel = lstTagMasterModel.Where(a => a.TagId == TagsId).ToList();
}
return lstTagMasterModel;
}
public async Task<TagMasterViewModel> SaveTagMasterDetails(TagMasterViewModel tagMasterViewModel)
{
TagMaster tagMasterDatails = new TagMaster()
{
//TagId= tagMasterViewModel.TagId,
TagName=tagMasterViewModel.TagName,
Created_By = "aaaa",
Modified_By = "aaa",
Created_Date = DateTime.Today,
Modified_Date = DateTime.Today
};
var tagObj = await _tagMasterHelper.CreateAsync(tagMasterDatails);
TagMasterViewModel tagMasterDetailsViewModel = new TagMasterViewModel
{
TagId = Convert.ToInt32(tagObj.TagId)
};
return tagMasterDetailsViewModel;
}
}
}
|
6694bb9b16f787854198f35fbdc1125e325fe9de
|
C#
|
rakeshkumartiwari/dot.net-console-application
|
/Question5/Program.cs
| 3.671875
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Question5
{
class Program
{
static void Main(string[] args)
{
//Que.4--write a program to swap min and max element in integer array.
//Input: arr[]={10,6,11,20,15,36,8}
//Outout:10,36,11,20,15,6,8
//Ans--
int[] arr = {10, 6, 11, 20, 15, 36, 8};
int j = 0;
int temp=0 ;
for (int i = 1; i < arr.Length; i++)
{
if (arr[j] < arr[i])
{
arr[temp] = arr[i];
arr[i] = arr[j];
arr[j] =arr[temp];
}
j ++;
}
Console.ReadLine();
}
}
}
|
85771c11383aa0cdfb99bbc073a8a341aa84aac6
|
C#
|
shendongnian/download4
|
/code7/1223011-32556924-99563432-2.cs
| 2.5625
| 3
|
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
|
7efc448360a8f1e02a85d38e44a0440bc4c012d8
|
C#
|
wesnerm/CompetitiveProgramming
|
/LeetCode/alien-dictionary.cs
| 3.203125
| 3
|
// 269. Alien Dictionary
// https://leetcode.com/problems/alien-dictionary
// Hard 23.2%
// 638.0417327467339
// Submission: https://leetcode.com/submissions/detail/68312484/
// Runtime: 168 ms
// Your runtime beats 7.14 % of csharp submissions.
public class Solution {
Dictionary<char, HashSet<char>> dict ;
Dictionary<char, int> depthMap;
HashSet<char>visited ;
HashSet<char> alphabet;
bool cycle;
public string AlienOrder(string[] words)
{
dict = new Dictionary<char, HashSet<char>>();
depthMap = new Dictionary<char, int>();
visited = new HashSet<char>();
alphabet = new HashSet<char>();
for (int i=0; i<words.Length; i++)
alphabet.UnionWith(words[i]);
for (int i=1; i<words.Length; i++)
{
var w1 = words[i-1].ToLower();
var w2 = words[i].ToLower();
int j=0;
for (j=0; j<w1.Length && j<w2.Length && w1[j]==w2[j]; j++)
{
}
if (j<w1.Length && j<w2.Length)
{
var c1 = w1[j];
var c2 = w2[j];
if (!dict.ContainsKey(c1))
dict[c1] = new HashSet<char>();
dict[c1].Add(c2);
}
}
foreach(var ch in dict.Keys)
TopSort(dict, ch);
if (cycle)
return "";
var list = alphabet.OrderByDescending(x=>depthMap.ContainsKey(x) ? depthMap[x] : 0).ToArray();
return new string(list);
}
public int TopSort(Dictionary<char, HashSet<char>> dict, char ch)
{
int depth;
if (depthMap.TryGetValue(ch, out depth))
return depth;
if (visited.Contains(ch))
{
depth = short.MaxValue;
cycle = true;
}
else
{
visited.Add(ch);
depth = 1;
if (dict.ContainsKey(ch))
foreach(var letter in dict[ch])
{
var childDepth = TopSort(dict, letter);
depth = Math.Max(depth, 1+childDepth);
}
visited.Remove(ch);
}
depthMap[ch] = depth;
return depth;
}
public static string Reverse( string s )
{
char[] charArray = s.ToCharArray();
Array.Reverse( charArray );
return new string( charArray );
}
}
|
d3b4a744a0c7dc1975bd6d6414fa94f58f731747
|
C#
|
pbakun/ClinicQueuev3
|
/QueueSystem/WebApp/Helpers/QueueDatabase.cs
| 2.859375
| 3
|
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApp.Models;
using WebApp.Utility;
namespace WebApp.DatabaseHelpers
{
public class QueueDatabase
{
public static void AddQueue(Queue queue)
{
using (SQLiteConnection conn = new SQLiteConnection(StaticDetails.dbFile))
{
//create table if there isn't any
conn.CreateTable<Queue>();
//check if there is a Queue with current's user id
var data = conn.Table<Queue>().Where(u => u.UserId == queue.UserId).FirstOrDefault();
if (data != null)
{
data.OwnerInitials = queue.OwnerInitials;
data.Timestamp = queue.Timestamp;
data.RoomNo = queue.RoomNo;
DatabaseHelper.Update(data);
}
//if not create new Queue in db
else
{
DatabaseHelper.Insert(queue);
}
}
}
public static void UpdateUsersQueue(Queue queue)
{
using (SQLiteConnection conn = new SQLiteConnection(DatabaseHelper.dbFile))
{
//find current queue update db
var data = conn.Table<Queue>().Where(u => u.UserId == queue.UserId);
if (data != null)
{
DatabaseHelper.Update(queue);
}
}
}
public static Queue FindQueue(string userId)
{
Queue user = new Queue();
if (userId != null)
{
using (SQLiteConnection conn = new SQLiteConnection(DatabaseHelper.dbFile))
{
conn.CreateTable<Queue>();
user = conn.Table<Queue>().Where(u => u.UserId == userId).FirstOrDefault();
}
}
return user;
}
public static Queue FindQueueByRoomNo(int? roomNo)
{
Queue user = new Queue();
if (roomNo != null)
{
using (SQLiteConnection conn = new SQLiteConnection(DatabaseHelper.dbFile))
{
conn.CreateTable<Queue>();
user = conn.Table<Queue>().Where(u => u.RoomNo == roomNo).OrderBy(t => t.Timestamp).FirstOrDefault();
}
}
return user;
}
public static List<Queue> ReadDatabase()
{
List<Queue> user;
using (SQLiteConnection conn = new SQLiteConnection(DatabaseHelper.dbFile))
{
user = conn.Table<Queue>().ToList();
//conn.Delete(user[1]);
}
return user;
}
}
}
|
8f014d3b8ee40604cd2801306ff2fa20ace3fd6f
|
C#
|
Saylala/kontur-internship-task
|
/Kontur.GameStats.Server/StatisticsUpdaters/PopularServersUpdater.cs
| 2.5625
| 3
|
using System.Linq;
using Kontur.GameStats.Server.Database;
using Kontur.GameStats.Server.Models.DatabaseEntries;
namespace Kontur.GameStats.Server.StatisticsUpdaters
{
public class PopularServersUpdater : IStatisticsUpdater
{
public void Update(MatchInfoEntry infoEntry, DatabaseContext databaseContext)
{
const int maxServersCount = 50;
var popularServers = databaseContext.PopularServers.OrderByDescending(x => x.AverageMatchesPerDay).ToList();
var serverStatistics = databaseContext.ServerStatistics.Find(infoEntry.Endpoint);
var serverInfo = databaseContext.Servers.Find(infoEntry.Endpoint);
if (serverStatistics == null || serverInfo == null)
return;
var serverName = serverInfo.Name;
var previous = popularServers.Find(x => x.Endpoint == serverInfo.Endpoint);
if (previous != null)
previous.AverageMatchesPerDay = serverStatistics.AverageMatchesPerDay;
else if (popularServers.Count < maxServersCount)
databaseContext.PopularServers.Add(new PopularServerEntry
{
Endpoint = infoEntry.Endpoint,
Name = serverName,
AverageMatchesPerDay = serverStatistics.AverageMatchesPerDay
});
else if (popularServers[popularServers.Count - 1].AverageMatchesPerDay < serverStatistics.AverageMatchesPerDay)
{
databaseContext.PopularServers.Remove(popularServers[popularServers.Count - 1]);
databaseContext.PopularServers.Add(new PopularServerEntry
{
Endpoint = infoEntry.Endpoint,
Name = serverName,
AverageMatchesPerDay = serverStatistics.AverageMatchesPerDay
});
}
}
}
}
|
77809b680f542930dae0e3716bec72688cb5b635
|
C#
|
Robert8034/Mealz
|
/ModerationService/DAL/ModerationCache.cs
| 2.828125
| 3
|
using Microsoft.EntityFrameworkCore;
using ModerationService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ModerationService.DAL
{
public class ModerationCache : IModerationCache
{
public List<Report> reports;
public List<Request> requests;
public bool databaseOffline;
public ModerationCache()
{
reports = new List<Report>();
requests = new List<Request>();
}
public void Initialize(ModerationContext moderationContext)
{
for (int i = 1; i < 5; i++)
{
if (moderationContext.Database.CanConnect())
{
requests = moderationContext.Requests.AsNoTracking().ToList();
reports = moderationContext.Reports.AsNoTracking().ToList();
databaseOffline = false;
break;
}
databaseOffline = true;
Console.WriteLine("Connection failed, attempt " + i + "/5");
System.Threading.Thread.Sleep(3000);
if (i == 5)
{
Console.WriteLine("ModerationDB is offline, data could not be cached");
}
}
}
public bool CheckIfDatabaseIsOffline()
{
return databaseOffline;
}
public void SetDatabaseOffline(bool databaseOffline)
{
this.databaseOffline = databaseOffline;
}
public List<Report> GetCachedReports()
{
return reports;
}
public List<Request> GetCachedRequests()
{
return requests;
}
public void SetCachedReports(List<Report> reports)
{
this.reports = reports;
}
public void SetCachedRequests(List<Request> requests)
{
this.requests = requests;
}
}
}
|
01a3f85b94c6c14dd60f7bea737ad62bdca4fa7f
|
C#
|
raojala/oop-koti
|
/labra3_tehtava_4/Vechile.cs
| 3.15625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JAMK.IT
{
class Vechile
{
/* Luo Vehicle-luokka seuraavien tietojen mukaisesti:
ominaisuudet
Name:string
Speed:int
Tyres:int
toiminnot
PrintData(), tulostaa Vehiclen ominaisuudet näytölle
ToString():string, palauttaa kaikki Vehiclen ominaisuudet yhtenä merkkijonona
Toteuta Vehicle-luokan ohjelmointi sekä pääohjelma, jolla luot olion Vehicle-luokasta.
Muuta olion arvoja ja tulosta olion arvoja konsolille.
*/
public string Name { get; }
int speed;
public int Speed
{
get
{
return speed;
}
set
{
if (!(value >= 0 && value <= 200))
speed = value;
else
speed = 0;
}
}
int tyres;
public int Tyres {
get
{
return tyres;
}
set
{
if (!(value >= 10 && value <= 25))
tyres = 14;
else
tyres = value;
}
}
public Vechile (string name, int vechileSpeed, int tires)
{
if (!(speed >= 0 && speed <= 200))
vechileSpeed = 0;
if (tyres >= 10 && tyres <= 25)
tires = 14;
speed = vechileSpeed;
tyres = tires;
Name = name;
}
public void PrintData()
{
Console.WriteLine("Vechile: " + Name);
Console.WriteLine("Speed: " + Speed);
Console.WriteLine("Tyres: " + Tyres);
}
public override string ToString()
{
string s = Name + ", " + Speed + ", " + Tyres;
return "";
}
}
}
|
e61ffeaf0aa4e3f5e7c90db171bd77f95d46b9e5
|
C#
|
settamaF/PixelGame
|
/Assets/Scripts/Utils/Utils.cs
| 2.859375
| 3
|
//******************************************************************************
// Author: Frédéric SETTAMA
//******************************************************************************
using UnityEngine;
using System.Security.Cryptography;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
#endif
//******************************************************************************
public static class Utils
{
// Encrypt the specified plainText using MD5 hash.
public static string Encrypt( string plainText )
{
// Calculate MD5 hash from input
MD5.Create();
MD5 md5 = MD5.Create();
byte[] inputBytes = Encoding.ASCII.GetBytes( plainText );
byte[] hash = md5.ComputeHash( inputBytes );
// Convert byte array to hex string
var stringBuilder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
stringBuilder.Append(hash[i].ToString("X2"));
}
return stringBuilder.ToString();
}
public static string TextToKey(string value)
{
if (string.IsNullOrEmpty(value))
return "";
if (value[0] == '[' && value[value.Length - 1] == ']')
return value;
return "[" + value.ToUpper() + "]";
}
#if UNITY_EDITOR
/// <summary>
/// Create new asset from <see cref="ScriptableObject"/> type with unique name at
/// selected folder in project window. Asset creation can be cancelled by pressing
/// escape key when asset is initially being named.
/// </summary>
/// <typeparam name="T">Type of scriptable object.</typeparam>
public static T CreateAsset<T>(string pathModel, string fileName) where T : ScriptableObject
{
var asset = ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(asset, pathModel + "/" + fileName + ".asset");
return asset;
}
#endif
}
|
533d23f574e3ba99b487b346f5f0456ff3fc19b0
|
C#
|
yanxiaodi/CurrencyExchanger
|
/YanSoft.CurrencyExchanger/src/YanSoft.CurrencyExchanger.Core/Utils/CurrencyHelper.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using MvvmCross;
using YanSoft.CurrencyExchanger.Core.Common;
namespace YanSoft.CurrencyExchanger.Core.Utils
{
public static class CurrencyHelper
{
public static string FormatCurrencyAmount(decimal amount, string cultureName)
{
//TODO
var appSettings = Mvx.IoCProvider.Resolve<AppSettings>();
if (appSettings.IsLocalizedCurrencySymbolEnabled)
{
string currencyFormat = string.Format("C{0}", appSettings.DecimalPrecision);
if (string.IsNullOrEmpty(cultureName))
{
CultureInfo ci = CultureInfo.CurrentCulture;
return amount.ToString(currencyFormat, ci);
}
else
{
string result = amount.ToString();
try
{
CultureInfo ci = new CultureInfo(cultureName);
result = amount.ToString(currencyFormat, ci);
}
catch
{
CultureInfo ci = CultureInfo.CurrentCulture;
result = amount.ToString(currencyFormat, ci);
}
return result;
}
}
else
{
string numberFormat = string.Format("N{0}", appSettings.DecimalPrecision);
return amount.ToString(numberFormat);
}
}
}
}
|
4cdd6ce1462609d757dea0a72b156e154b421d04
|
C#
|
adam0309/UnsafeCodePresentation
|
/PointersPresentation/ColorFilters/UnsafeColorFilter.cs
| 2.9375
| 3
|
using System.Drawing;
using System.Drawing.Imaging;
using PointersPresentation.Filters.Interfaces;
namespace PointersPresentation.Filters.ColorFilters
{
public unsafe class UnsafeColorFilter: IFilter
{
public Bitmap FilterImage(Bitmap bitmap)
{
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
int wysokosc = bitmapData.Height;
int szerokosc = bitmapData.Width;
unsafe
{
byte* ptr = (byte*)bitmapData.Scan0.ToPointer();
for (int i = 0; i < wysokosc; i++)
{
for (int j = 0; j < szerokosc; j++, ptr += 3)
{
if (*ptr == 230 && *(ptr + 1) == 192 && *(ptr + 2) == 104) continue;
{
*ptr = 0;
*(ptr + 1) = 0;
*(ptr + 2) = 0;
}
}
//Calculating next row offset
ptr += bitmapData.Stride - (bitmapData.Width * 3);
}
}
bitmap.UnlockBits(bitmapData);
return bitmap;
}
void costam(byte* pointer)
{
}
}
}
|
9e2d700331333c16f11e40a9be4d8a5b8a43d58d
|
C#
|
yoshuhlnak/IControl
|
/InputControl/Service/UserService.cs
| 2.84375
| 3
|
using System;
namespace InputControl.Service
{
public class UserService : IUserService
{
private readonly string _login;
public UserService()
{
string[] cmdLineArgs = Environment.GetCommandLineArgs();
if (cmdLineArgs.Length > 1)
_login = cmdLineArgs[1];
else
_login = Environment.UserName;
}
public string Login {
get { return _login; }
}
}
}
|
5fce62ac5c56809e3b67d43de4d0b1f43500eeaa
|
C#
|
wgimson/MvcBeerStore
|
/MvcBeerStore/Models/SampleData.cs
| 2.53125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcBeerStore.Models
{
public class SampleData : DropCreateDatabaseAlways<BeerStoreEntities>
{
protected override void Seed(BeerStoreEntities context)
{
var styles = new List<Style>
{
new Style { Name = "Imperial IPA" },
new Style { Name = "IPA" },
new Style { Name = "Russian Imperial Stout" },
new Style { Name = "Belgian Dubbel" },
new Style { Name = "Belgian Quadruppel" },
new Style { Name = "American Barleywine" },
new Style { Name = "Porter" },
new Style { Name = "Lambic" },
new Style { Name = "Saison" },
new Style { Name = "Scotch Ale" }
};
var breweries = new List<Brewery>
{
new Brewery { Name = "The Alchemist" },
new Brewery { Name = "Russian River Brewing Company" },
new Brewery { Name = "Three Floyds Brewing Company" },
new Brewery { Name = "Founders Brewing Company" },
new Brewery { Name = "Brouwerij Westvleteren" },
new Brewery { Name = "Goose Island Beer Company" },
new Brewery { Name = "Firestone Walker Brewing Company" },
new Brewery { Name = "Deschutes Brewery" },
new Brewery { Name = "Brasserie Cantillon" },
new Brewery { Name = "Lawson's Finest Liquids" },
new Brewery { Name = "Bell's Brewery" },
new Brewery { Name = "Cigar City Brewing" },
new Brewery { Name = "Alpine Brewery" },
new Brewery { Name = "Stone Brewery" },
new Brewery { Name = "Rochefort Brewery" },
new Brewery { Name = "Great Divide Brewing Company" },
new Brewery { Name = "Boulevard Brewing Company" },
};
new List<Beer>
{
new Beer { Name = "Hopslam", Style = styles.Single(s => s.Name == "Imperial IPA"), Price = 8.99M, Brewery = breweries.Single(b => b.Name == "Bell's Brewery"), BeerArtUrl = "/Content/Images/hopslam.jpg" },
new Beer { Name = "Nelson", Style = styles.Single(s => s.Name == "IPA"), Price = 10.99M, Brewery = breweries.Single(b => b.Name == "Alpine Brewery"), BeerArtUrl = "/Content/Images/nelson.jpg" },
new Beer { Name = "Imperial Russian Stout", Style = styles.Single(s => s.Name == "Russian Imperial Stout"), Price = 12.99M, Brewery = breweries.Single(b => b.Name == "Stone Brewery"), BeerArtUrl = "/Content/Images/imperialrussianstout.jpg" },
new Beer { Name = "Rochefort 8", Style = styles.Single(s => s.Name == "Belgian Dubbel"), Price = 8.99M, Brewery = breweries.Single(b => b.Name == "Rochefort Brewery"), BeerArtUrl = "/Content/Images/rochefort8.jpg" },
new Beer { Name = "Westvleteren 12", Style = styles.Single(s => s.Name == "Belgian Quadruppel"), Price = 20.99m, Brewery = breweries.Single(b => b.Name == "Brouwerij Westvleteren"), BeerArtUrl = "/Content/Images/westvleteren12.jpg" },
new Beer { Name = "Old Ruffian", Style = styles.Single(s => s.Name == "American Barleywine"), Price = 14.99M, Brewery = breweries.Single(b => b.Name == "Great Divide Brewing Company"), BeerArtUrl = "/Content/Images/oldruffian.jpg" },
new Beer { Name = "Black Butte Porter", Style = styles.Single(s => s.Name == "Porter"), Price = 7.99M, Brewery = breweries.Single(b => b.Name == "Deschutes Brewery"), BeerArtUrl = "/Content/Images/blackbutteporter.jpg" },
new Beer { Name = "Fou' Foune", Style = styles.Single(s => s.Name == "Lambic"), Price = 60.99M, Brewery = breweries.Single(b => b.Name == "Brasserie Cantillon"), BeerArtUrl = "/Content/Images/foufoune.jpg" },
new Beer { Name = "Saison-Brett", Style = styles.Single(s => s.Name == "Saison"), Price = 13.99M, Brewery = breweries.Single(b => b.Name == "Boulevard Brewing Company"), BeerArtUrl = "/Content/Images/saisonbrett.jpg" },
new Beer { Name = "Backwoods Bastard", Style = styles.Single(s => s.Name == "Scotch Ale"), Price = 11.99M, Brewery = breweries.Single(b => b.Name == "Founders Brewing Company"), BeerArtUrl = "/Content/Images/backwoodsbastard.jpg" }
}.ForEach(b => context.Beers.Add(b));
}
}
}
|
9c1ca6d021606df2a566ac4c7998c17fc3a83fcf
|
C#
|
skolarajak/Grupa5_Cas27
|
/Cas27/Ivica/PrvaGodina.cs
| 2.625
| 3
|
using System;
namespace Cas27.Ivica
{
class PrvaGodina : Udzbenici
{
public bool Iznajmljena { get; set; } = true;
/*
* Method overloading:
* public void Procitaj(bool DaLiJeIznajmljena)
*/
new public void Procitaj()
{
if (Iznajmljena)
{
Console.WriteLine("Iznajmili ste {0}, izdatu {1} godine", Naslov, GodinaIzdavanja);
}
else
{
Console.WriteLine("Niste Iznajmili knjigu {0}, izdatu {1} godine", Naslov, GodinaIzdavanja);
}
}
}
}
|
0b3cd965ad0472cd0df6c7662351fa81535567ac
|
C#
|
derek-cap/FodicomTest
|
/DicomViewer/Models/PixelData.cs
| 2.828125
| 3
|
using Dicom.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DicomViewer.Models
{
public class PixelData
{
private int _width;
private int _height;
private int _bpp;
private byte[] _data;
public PixelData(int wdth, int hgt, int numOfByte)
{
_width = wdth;
_height = hgt;
_bpp = numOfByte;
}
public int Width => _width;
public int Height => _height;
public int BPP => _bpp;
public byte[] Data
{
get { return _data; }
set { _data = value; }
}
}
}
|
b1329b04157f4f621669a8b76518e540bf535a51
|
C#
|
marksman315/HUTWeb
|
/HUTWeb/Helpers/HttpHelper.cs
| 2.921875
| 3
|
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace HUTWeb.Helpers
{
public static class HttpHelper
{
public static async Task<string> GetValues(Uri uri)
{
using (var client = GetHttpClient())
{
var result = await client.GetStringAsync(uri).ConfigureAwait(false);
return result;
}
}
public static async Task<string> PostValues(Uri uri, object model)
{
var httpContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
using (var client = GetHttpClient())
{
var httpResponse = await client.PostAsync(uri, httpContent).ConfigureAwait(false);
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseContent.ToString();
}
}
return null;
}
public static async Task<string> PutValues(Uri uri, object model)
{
var httpContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
using (var client = GetHttpClient())
{
var httpResponse = await client.PutAsync(uri, httpContent).ConfigureAwait(false);
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseContent.ToString();
}
}
return null;
}
private static HttpClient GetHttpClient()
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
}
}
|
1a5457ce989692cbba3f124c85c05067da119ee2
|
C#
|
NethermindEth/rocksdb-sharp
|
/examples/SimpleExampleHighLevel/Program.cs
| 2.921875
| 3
|
using RocksDbSharp;
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace SimpleExampleHighLevel
{
class Program
{
static void Main(string[] args)
{
string temp = Path.GetTempPath();
string path = Environment.ExpandEnvironmentVariables(Path.Combine(temp, "rocksdb_simple_hl_example"));
// the Options class contains a set of configurable DB options
// that determines the behavior of a database
// Why is the syntax, SetXXX(), not very C#-like? See Options for an explanation
var options = new DbOptions()
.SetCreateIfMissing(true)
.EnableStatistics();
using (var db = RocksDb.Open(options, path))
{
try
{
{
// With strings
string value = db.Get("key");
db.Put("key", "value");
value = db.Get("key");
string iWillBeNull = db.Get("non-existent-key");
db.Remove("key");
}
{
// With bytes
var key = Encoding.UTF8.GetBytes("key");
byte[] value = Encoding.UTF8.GetBytes("value");
db.Put(key, value);
value = db.Get(key);
byte[] iWillBeNull = db.Get(new byte[] { 0, 1, 2 });
db.Remove(key);
db.Put(key, new byte[] { 0, 1, 2, 3, 4, 5, 6, 7 });
}
{
// With buffers
var key = Encoding.UTF8.GetBytes("key");
var buffer = new byte[100];
long length = db.Get(key, buffer, 0, buffer.Length);
}
{
// Removal of non-existent keys
db.Remove("I don't exist");
}
{
// Write batches
// With strings
using (WriteBatch batch = new WriteBatch()
.Put("one", "uno")
.Put("two", "deuce")
.Put("two", "dos")
.Put("three", "tres"))
{
db.Write(batch);
}
// With bytes
var utf8 = Encoding.UTF8;
using (WriteBatch batch = new WriteBatch()
.Put(utf8.GetBytes("four"), new byte[] { 4, 4, 4 } )
.Put(utf8.GetBytes("five"), new byte[] { 5, 5, 5 } ))
{
db.Write(batch);
}
}
{
// Snapshots
using (var snapshot = db.CreateSnapshot())
{
var before = db.Get("one");
db.Put("one", "1");
var useSnapshot = new ReadOptions()
.SetSnapshot(snapshot);
// the database value was written
Debug.Assert(db.Get("one") == "1");
// but the snapshot still sees the old version
var after = db.Get("one", readOptions: useSnapshot);
Debug.Assert(after == before);
}
}
var two = db.Get("two");
Debug.Assert(two == "dos");
{
// Iterators
using (var iterator = db.NewIterator(
readOptions: new ReadOptions()
.SetIterateUpperBound("t")
))
{
iterator.Seek("k");
Debug.Assert(iterator.Valid());
Debug.Assert(iterator.StringKey() == "key");
iterator.Next();
Debug.Assert(iterator.Valid());
Debug.Assert(iterator.StringKey() == "one");
Debug.Assert(iterator.StringValue() == "1");
iterator.Next();
Debug.Assert(!iterator.Valid());
}
}
}
catch (RocksDbException)
{
}
}
}
}
}
|
35dcd80bc3efad18dde171e6c7b25e6d5eae8933
|
C#
|
jayabharathiCIT/DICT_Website
|
/testmaster2/ChangePassword.aspx.cs
| 2.515625
| 3
|
using MySql.Data.MySqlClient;
using System;
using System.Configuration;
using System.Data;
namespace DICT_Website
{
public partial class ChangePassword : System.Web.UI.Page
{
// string connectionString = @"Server=localhost;Database=dict website;Uid=root;Pwd=1234;";
string strConnString = ConfigurationManager.ConnectionStrings["DICTMySqlConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
// check user is authenticated .
// Start Check authorised user
if (Session["RegID"] == null)
Response.Redirect("~/Login.aspx");
else
{
String userid = Convert.ToString((int)Session["RegID"]);
String username = Session["Username"].ToString();
//String userrole = Session["Role"].ToString();
lbluserInfo.Text = "Welcome , " + username + " ";
}
// End Check authorised user
}
protected void btnChangePassword_Click(object sender, EventArgs e)
{
if ((txtPassword1.Text.Length < 5) || (txtConfirmPassword.Text.Length < 5))
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Password should be numeric between 6 to 10!!')", true);
else if ((txtPassword1.Text.Length > 10) || (txtConfirmPassword.Text.Length > 10))
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Password should be numeric between 6 to 10!!')", true);
else
{
int validResult = CheckAllRegisterValidation();
if (validResult == 1)
{
try
{
lblErrorConfirmPassword.Text = "";
using (MySqlConnection sqlCon = new MySqlConnection(strConnString))
{
sqlCon.Open();
MySqlDataAdapter sqlCmd = new MySqlDataAdapter("sp_CheckPassword", sqlCon);
sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlCmd.SelectCommand.Parameters.AddWithValue("P_Register_ID", txtID.Text);
sqlCmd.SelectCommand.Parameters.AddWithValue("P_Password", txtPassword1.Text);
//string postCreatedDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
//sqlCmd.SelectCommand.Parameters.AddWithValue("P_Date_Change_Password", postCreatedDate);
//sqlCmd.SelectCommand.ExecuteNonQuery();
DataTable dtbl = new DataTable();
sqlCmd.Fill(dtbl);
string username = dtbl.Rows[0][0].ToString();
string OLdpassword = dtbl.Rows[0][1].ToString();
if (OLdpassword == txtPassword1.Text)
{
if (txtNewPassword.Text == txtConfirmPassword.Text)
{
DataTable dtblCon = new DataTable();
MySqlDataAdapter sqlPass = new MySqlDataAdapter("sp_PasswordChange", sqlCon);
sqlPass.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlPass.SelectCommand.Parameters.AddWithValue("P_Register_ID", txtID.Text);
sqlPass.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlPass.SelectCommand.Parameters.AddWithValue("P_Password", txtNewPassword.Text);
sqlPass.SelectCommand.CommandType = CommandType.StoredProcedure;
string postCreatedDate1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
sqlPass.SelectCommand.Parameters.AddWithValue("P_Date_Change_Password", postCreatedDate1);
sqlPass.SelectCommand.ExecuteNonQuery();
Response.Write("<script>alert('successfully change the password!!'); ");
Response.Write("window.location='ForumHomePage.aspx'</script>");
//ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('successfully change the password!!');window.location='DICT_Website.ForumHomePage.aspx';", true);
//lblSuccessMessage.Text = "successfully change the password!";
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Password miss match!!')", true);
//lblErrorConfirmPassword.ForeColor = System.Drawing.Color.Red;
//lblErrorConfirmPassword.Text = "Password miss match";
}
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Current password is incorrect!!')", true);
//lblErrorConfirmPassword.ForeColor = System.Drawing.Color.Red;
//lblErrorPassword.Text = "Current password is incorrect";
}
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = ex.Message;
}
}
}
}
public int CheckAllRegisterValidation()
{
if (txtID.Text.Length == 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Your ID can not be blank !!')", true);
//lblErrorID.Text = "*** Your ID can not be blank ***";
return 0;
}
else if (txtPassword1.Text.Length == 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Password can not be blank !!')", true);
// lblErrorPassword.Text = "*** Password can not be blank ***";
return 0;
}
else if (txtNewPassword.Text.Length == 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('New password can not be blank !!')", true);
//lblErrorNewPassword.Text = "*** New password can not be blank ***";
return 0;
}
else if (txtConfirmPassword.Text.Length == 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Confirm password can not be blank!!')", true);
//lblErrorConfirmPassword.Text = "*** Confirm password can not be blank ***";
return 0;
}
else
{
return 1;
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Response.Redirect("~/ForumHomePage.aspx");
}
protected void submit_Click(object sender, EventArgs e)
{
Response.Redirect("~/ForumHomePage.aspx");
}
protected void ddlLogin_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlLogin.SelectedItem.Value == "4")
{
//ChangePassword
Response.Redirect("~/AdminProfilePage.aspx");
}
if (ddlLogin.SelectedItem.Value == "1")
{
//ChangePassword
Response.Redirect("~/ChangePassword.aspx");
}
if (ddlLogin.SelectedItem.Value == "2")
{
//DeleteAccount
Response.Redirect("~/DeleteAccount.aspx");
}
if (ddlLogin.SelectedItem.Value == "3")
{
//Logout
//clear session variables
Session.Clear();
Session.Remove("RegID");
Session.Remove("Username");
//redirect to login page
Response.Redirect("~/Login.aspx");
}
}
}
}
|
fb7c789066bdffc92b703debd22a06b61937405e
|
C#
|
pcresswell/authorize
|
/Subject.cs
| 3.203125
| 3
|
//
// Subject.cs
//
// Author:
// peter <pcresswell@gmail.com>
//
// Copyright (c) 2015 peter
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
namespace Authorize
{
using System;
using Newtonsoft.Json;
/// <summary>
/// A subject. Subjects are targets for actions. They can represent either a Type
/// or an instance of a Type.
/// </summary>
[JsonObjectAttribute]
public class Subject
{
public Subject()
{
this.Identity = string.Empty;
}
/// <summary>
/// Initializes a new instance of the <see cref="Authorize.Subject"/> class.
/// </summary>
/// <param name="subject">The subject.</param>
public Subject(object subject)
{
Type t = subject as Type;
if (t != null)
{
//subject is a Type
this.Type = (Type)subject;
}
else
{
this.Type = subject.GetType();
this.Identity = subject.GetHashCode().ToString();
}
}
/// <summary>
/// Gets the type that this subject applies against.
/// </summary>
/// <value>The type.</value>
[JsonPropertyAttribute]
public Type Type { get; private set; }
/// <summary>
/// Gets the instance identity.
/// </summary>
/// <value>The identity.</value>
[JsonPropertyAttribute]
public object Identity { get; private set; }
/// <summary>
/// Does this subject apply against the given subject.
/// Four possible situations
/// 1. We are a type and subject is a type - only types must match
/// 2. We are a type and subject is instance of the type - only types must match
/// 3. We are an instance and subject is a type - false
/// 4. We are an instance and subject is an instance - same type and Identity
/// </summary>
/// <returns><c>true</c>, if to was appliesed, <c>false</c> otherwise.</returns>
/// <param name="subject">The subject.</param>
public bool AppliesTo(object subject)
{
// 1. We are a type
if (this.Identity == null)
{
// 2. They are a type
Type t = subject as Type;
if (t != null)
{
return subject == this.Type;
}
else
{
return subject.GetType().Equals(this.Type);
}
}
else
{
// 3. We are an instance and they are a type.
Type t = subject as Type;
if (t != null)
{
return false;
}
else
{
// 4. we are an instance and they are as well
// Type does not match
if (!this.Type.Equals(subject.GetType()))
{
return false;
}
else
{
return this.Identity.Equals(subject.GetHashCode().ToString());
}
}
}
}
}
}
|
d74d76f354aa238f7aa161a053c598b8e90fc3a6
|
C#
|
andersonom/Samples
|
/dotnet/FW 4.6/SimpleLogin/SimpleLogin.Application/AppServiceBase.cs
| 2.65625
| 3
|
using SimpleLogin.Application;
using SimpleLogin.Application.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleLogin.Application
{
public class AppServiceBase<TEntity> : IDisposable, IAppServiceBase<TEntity> where TEntity : class
{
private readonly IAppServiceBase<TEntity> _appServiceBase;
public AppServiceBase(AppServiceBase<TEntity> appServiceBase)
{
_appServiceBase = appServiceBase;
}
public void Add(TEntity obj)
{
_appServiceBase.Add(obj);
}
public void Dispose()
{
_appServiceBase.Dispose();
}
public IEnumerable<TEntity> GetAll()
{
return _appServiceBase.GetAll();
}
public TEntity GetById(int id)
{
return _appServiceBase.GetById(id);
}
public void Remove(TEntity obj)
{
_appServiceBase.Remove(obj);
}
public void Update(TEntity obj)
{
_appServiceBase.Update(obj);
}
}
}
|
18bc36229d94d222d3831e2003e83c3aa0dda937
|
C#
|
UShandruk/Pub
|
/Other/PerfomanceLab/Task1/Task1/Model/Square.cs
| 3.515625
| 4
|
using System;
namespace Task1.Model
{
public class Square : Figure
{
private double side;
public Square(double side)
{
this.side = side;
}
public override double CalculateArea()
{
double area = side * side;
return Math.Round(area, 3);
}
}
}
|
3338b01cda9d0158a69befff917fd6cb46a618ab
|
C#
|
abuzaforfagun/ClientManagerPortal.NETCore.Angular
|
/ClientManagerPortal.NET Core.Angular/API/ClientsController.cs
| 2.59375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ClientManagerPortal.NET_Core.Angular.core.Models;
using AutoMapper;
using ClientManagerPortal.NET_Core.Angular.Presistance;
namespace ClientManagerPortal.NET_Core.Angular.API
{
[Produces("application/json")]
public class ClientsController : Controller
{
private List<Client> clients;
private readonly IMapper mapper;
public ClientsController(IMapper mapper)
{
clients = new List<Client>()
{
new Client()
{
Id=1,
Name="Client 1",
Projects={
new Project(){Id=1, Name="Project 1"},
new Project(){Id=2, Name="Project 2",},
new Project(){Id=3, Name="Project 3"},
}
},
new Client()
{
Id=2,
Name="Client 2",
Projects={
new Project(){Id=1, Name="Project 1"},
new Project(){Id=2, Name="Project 2",},
new Project(){Id=3, Name="Project 3"},
new Project(){Id=4, Name="Project 4"},
}
},
new Client()
{
Id=3,
Name="Client 3",
Projects={
new Project(){Id=1, Name="Project 1"},
new Project(){Id=2, Name="Project 2",},
new Project(){Id=3, Name="Project 3"},
}
},new Client()
{
Id=4,
Name="Client 4",
Projects={
new Project(){Id=1, Name="Project 1"},
new Project(){Id=2, Name="Project 2",},
new Project(){Id=3, Name="Project 3"},
}
},
};
this.mapper = mapper;
}
[HttpGet]
[Route("api/Clients")]
public IActionResult GetAll()
{
List<ClientPresistance> res = mapper.Map<List<Client>, List<ClientPresistance>>(clients);
return Ok(res);
}
[HttpGet]
[Route("api/Clients/{id}")]
public IActionResult GetOne(int id)
{
Client client;
client = clients.SingleOrDefault(c=>c.Id==id);
if(client==null){
return NotFound();
}
return Ok(client);
}
[HttpDelete]
[Route("api/Clients/{id}")]
public IActionResult Delete(int id)
{
//TODO: Implement Realistic Implementation
var c = this.clients.Find(obj=>obj.Id==id);
this.clients.Remove(c);
return Ok();
}
[HttpPost]
[Route("api/Clients")]
public IActionResult Add(ClientPresistance client)
{
var c = mapper.Map<Client>(client);
c.Id = clients.Last().Id+1;
this.clients.Add(c);
return Ok(c);
}
}
}
|
1a33bbb4dffe00b4d9816d7a7a4a1596c0d5c9eb
|
C#
|
aledsribeiro/TDDNUnit
|
/TDD/LeilaoTest.cs
| 2.859375
| 3
|
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Caelum.Leilao
{
[TestFixture]
public class LeilaoTest
{
[Test]
public void DeveReceberUmLance()
{
Leilao leilao = new Leilao("Notebook");
Assert.AreEqual(0, leilao.Lances.Count);
leilao.Propoe(new Lance(new Usuario("Alessandra"), 2000));
Assert.AreEqual(1, leilao.Lances.Count);
Assert.AreEqual(2000, leilao.Lances[0].Valor, 0.00001);
}
[Test]
public void DeveReceberVariosLances()
{
Leilao leilao = new Leilao("Notebook");
leilao.Propoe(new Lance(new Usuario("Alessandra"), 1550));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 1650));
Assert.AreEqual(2, leilao.Lances.Count);
Assert.AreEqual(1550, leilao.Lances[0].Valor, 0.00001);
Assert.AreEqual(1650, leilao.Lances[1].Valor, 0.00001);
}
[Test]
public void NaoDeveAceitarDoisLancesSeguidosDoMesmoUsuario()
{
Leilao leilao = new Leilao("Notebook");
leilao.Propoe(new Lance(new Usuario("Alessandra"), 1550));
leilao.Propoe(new Lance(new Usuario("Alessandra"), 1650));
Assert.AreEqual(1, leilao.Lances.Count);
Assert.AreEqual(1550, leilao.Lances[0].Valor, 0.00001);
}
[Test]
public void NãoDeveAceitarCincoLancesDeUmMesmoUsuario()
{
Leilao leilao = new Leilao("Notebook");
leilao.Propoe(new Lance(new Usuario("Alessandra"), 1550));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 1650));
leilao.Propoe(new Lance(new Usuario("Alessandra"), 2000));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 2250));
leilao.Propoe(new Lance(new Usuario("Alessandra"), 3500));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 3750));
leilao.Propoe(new Lance(new Usuario("Alessandra"), 4000));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 4250));
leilao.Propoe(new Lance(new Usuario("Alessandra"), 4500));
leilao.Propoe(new Lance(new Usuario("Jeffersonn"), 4750));
//deve ser igonrado
leilao.Propoe(new Lance(new Usuario("Alessandra"), 5000));
Assert.AreEqual(10, leilao.Lances.Count);
var ultimo = leilao.Lances.Count - 1;
Lance ultimoLance = leilao.Lances[ultimo];
Assert.AreEqual(4750, ultimoLance.Valor, 0.00001);
}
}
}
|
958c2a67bddeed63bc262474a181e248e19653b2
|
C#
|
marinewater/Nager.PublicSuffix
|
/src/Nager.PublicSuffix/Extensions/DomainDataStructureExtensions.cs
| 3
| 3
|
using System.Collections.Generic;
using System.Linq;
namespace Nager.PublicSuffix.Extensions
{
/// <summary>
/// <see cref="DomainDataStructure"/> extension methods to create the TLD Tree.
/// </summary>
public static class DomainDataStructureExtensions
{
/// <summary>
/// Add all the rules in <paramref name="tldRules"/> to <paramref name="structure"/>.
/// </summary>
/// <param name="structure">The structure to appened the rule.</param>
/// <param name="tldRules">The rules to append.</param>
public static void AddRules(this DomainDataStructure structure, IEnumerable<TldRule> tldRules)
{
foreach (var tldRule in tldRules)
{
structure.AddRule(tldRule);
}
}
/// <summary>
/// Add <paramref name="tldRule"/> to <paramref name="structure"/>.
/// </summary>
/// <param name="structure">The structure to appened the rule.</param>
/// <param name="tldRule">The rule to append.</param>
public static void AddRule(this DomainDataStructure structure, TldRule tldRule)
{
var parts = tldRule.Name.Split('.').Reverse().ToList();
for (var i = 0; i < parts.Count; i++)
{
var domainPart = parts[i];
if (parts.Count - 1 > i)
{
//Check if domain exists
if (!structure.Nested.ContainsKey(domainPart))
{
structure.Nested.Add(domainPart, new DomainDataStructure(domainPart));
}
structure = structure.Nested[domainPart];
continue;
}
//Check if domain exists
if (structure.Nested.ContainsKey(domainPart))
{
structure.Nested[domainPart].TldRule = tldRule;
continue;
}
structure.Nested.Add(domainPart, new DomainDataStructure(domainPart, tldRule));
}
}
}
}
|
2fb67ddd5bf1f5f2063ae8b76ed811566b5ffee0
|
C#
|
ArbuzovaTanya/ArbuzovaPatterns
|
/Observer/Woman.cs
| 3.6875
| 4
|
using System;
using System.Collections.Generic;
using System.Threading;
namespace Observer
{
public class Woman : IObservable
{
private readonly WomanInfo _info;
private readonly List<IObserver> _observers;
public Woman(WomanInfo info)
{
_info = info;
_observers = new List<IObserver>();
}
public void NotifyObservers()
{
foreach (var item in _observers)
item.Update(_info);
Thread.Sleep(1000);
}
public void RegisterObserver(IObserver o)
{
_observers.Add(o);
if (o is Man man)
Console.WriteLine($"'{man.Name}' подписался на '{_info.Name}'");
Thread.Sleep(1000);
}
public void RemoveObserver(IObserver o)
{
_observers.Remove(o);
if (o is Man man)
Console.WriteLine($"'{man.Name}' отписался от '{_info.Name}'");
Thread.Sleep(1000);
}
public void Say(string message)
{
_info.Messages.Add(message);
NotifyObservers();
}
}
}
|
15e22066920fd681952ccc79b82bc414072733ef
|
C#
|
yasinayata/CreateTokenApplication
|
/Encryption/BasicEncryption.cs
| 2.953125
| 3
|
using Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace CreateTokenApplication.Encryption
{
#region BasicEncryption
public static class BasicEncryption
{
#region BasicEncryptDecrypt
public static OperationResult BasicEncryptDecrypt(string Data, int EncryptionKey)
{
OperationResult opr = new OperationResult();
try
{
StringBuilder szInputStringBuild = new StringBuilder(Data);
StringBuilder szOutStringBuild = new StringBuilder(Data.Length);
char Textch;
for (int iCount = 0; iCount < Data.Length; iCount++)
{
Textch = szInputStringBuild[iCount];
Textch = (char)(Textch ^ EncryptionKey);
szOutStringBuild.Append(Textch);
opr.Message = szOutStringBuild.ToString();
}
}
catch (Exception exception)
{
Console.WriteLine($"Exception : {exception.Message}");
opr.Result = false;
opr.Message = Data;
}
return opr;
}
#endregion
}
#endregion
}
|
7df58dc708f5a0d8de1b7ce7f5305c63e252c345
|
C#
|
Emberglo/taskmastercsharp
|
/Repositories/ListTaskRepository.cs
| 2.6875
| 3
|
using System.Collections.Generic;
using System.Data;
using Dapper;
using taskmastercsharp.Models;
namespace taskmastercsharp.Repositories
{
public class ListTaskRepository
{
private readonly IDbConnection _db;
public ListTaskRepository(IDbConnection db)
{
_db = db;
}
public int Create(ListTask newLt)
{
string sql = @"
INSERT INTO listtask
(listId, taskId, creatorId)
VALUES
(@ListId, @TaskId, @CreatorId);
SELECT LAST_INSERT_ID();";
return _db.ExecuteScalar<int>(sql, newLt);
}
internal IEnumerable<MyTask> GetTasksByListId(int listId)
{
string sql = @"
SELECT l.*,
lt.id as ListTaskId,
p.*
FROM listtask lt
JOIN tasks t ON t.id = lt.taskId
JOIN profiles p ON p.id = l.creatorId
WHERE listId = @listId;";
return _db.Query<ListTaskViewModel, Profile, ListTaskViewModel>(sql, (task, profile) => { task.Creator = profile; return task; }, new { listId }, splitOn: "id");
}
internal bool Remove(int id)
{
string sql = "DELETE from listtask WHERE id = @id";
int valid = _db.Execute(sql, new { id });
return valid > 0;
}
internal ListTask GetOne(int id)
{
string sql = @"SELECT * from listtask WHERE id = @id";
return _db.QueryFirstOrDefault<ListTask>(sql, new { id });
}
}
}
|
350ee979df2a2189991a3c8b6ca81d549762e307
|
C#
|
vasylynka/CustomerInquiry
|
/Core.Infrastructure/Dal/Queries/QueryBuilder.cs
| 2.59375
| 3
|
using System;
using System.Linq;
using System.Linq.Expressions;
namespace Core.Infrastructure.Dal.Queries
{
/// <summary>
/// Default query builder, builds query for getting all records
/// </summary>
/// <typeparam name="TEntity">Entity model type</typeparam>
public class QueryBuilder<TEntity> : IQueryBuilder<TEntity> where TEntity : class
{
public virtual IQuery<TEntity> Build(params Expression<Func<TEntity, object>>[] includeProperties)
{
return new EntityQuery<TEntity>(q => q.Query<TEntity>(), includeProperties);
}
public virtual IQuery<TEntity> Build(Func<IQueryableProvider, IQueryable<TEntity>> query, params Expression<Func<TEntity, object>>[] includeProperties)
{
return new EntityQuery<TEntity>(query, includeProperties);
}
}
}
|
d0dfec1123ec317bb3489e106854b07adb0031b5
|
C#
|
kaykayehnn/BookAnalytics
|
/BookAnalyticsTests/WordMatcherTests.cs
| 3.125
| 3
|
using _01_BookStatistics;
using NUnit.Framework;
namespace BookStatisticsTests
{
public class WordMatcherTests
{
[Test]
public void MatchesEnglishWords()
{
string text = "word";
string[] expected = { "word" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesCyrillicWords()
{
string text = "боза";
string[] expected = { "боза" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesAccentedWords()
{
string text = "Düsseldorf";
string[] expected = { "Düsseldorf" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesChineseWords()
{
string text = "北京市";
string[] expected = { "北京市" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesArabicWords()
{
string text = "إسرائيل";
string[] expected = { "إسرائيل" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesComplexWords()
{
string text = "voyez-vous";
string[] expected = { "voyez-vous" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesWordsWithApostrophes()
{
string text = "s’accuse";
string[] expected = { "s’accuse" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesNumbers()
{
string text = "42";
string[] expected = { "42" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesWordedNumbers()
{
string text = "42nd";
string[] expected = { "42nd" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesWordedNumbersCyrillic()
{
string text = "42-ри";
string[] expected = { "42-ри" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesNegativeNumbers()
{
string text = "-42";
string[] expected = { "-42" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesOnlyWordCharacters()
{
string text = "42°";
string[] expected = { "42" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
[Ignore("Too difficult to fix")]
// This tests fails. It would be really difficult to develop a proper regex for this, but
// it is left for future reference.
public void MatchesNumberPeriods()
{
string text = "2011-2012";
string[] expected = { "2011", "2012" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesWordsWithNumbers()
{
string text = "C4";
string[] expected = { "C4" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesWordsInInvertedCommas()
{
string text = "„о“-то";
string[] expected = { "„о“-то" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
[Test]
public void MatchesSentencesCorrectly()
{
string text = "The 42 box is s’accuse.";
string[] expected = { "The", "42", "box", "is", "s’accuse" };
string[] actual = WordMatcher.ExtractWords(text);
Assert.AreEqual(expected, actual);
}
}
}
|
6f25b4376e9e41260232c6a51af32aaf00e8537d
|
C#
|
MaxNagibator/TechDevelopSoft
|
/SchoolManagement/GUI/GroupsForm.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using SchoolManagement.School;
namespace SchoolManagement.GUI
{
public partial class GroupsForm : Form
{
public bool IsSelectedMode;
public Group SelectedGroup;
private List<Group> _groups;
public GroupsForm()
{
InitializeComponent();
RefreshInfo();
}
private void GroupsForm_Load(object sender, EventArgs e)
{
CheckSelectedButton();
RefreshInfo();
}
private void CheckSelectedButton()
{
uiSelectToolStripButton.Visible = IsSelectedMode;
}
private void RefreshInfo()
{
_groups = DatabaseManager.GetGroups();
uiMainDataGridView.DataSource = _groups;
var dataGridViewColumn = uiMainDataGridView.Columns["Id"];
if (dataGridViewColumn != null) dataGridViewColumn.Visible = false;
Globals.SetColumnWidthAndFormHeight(this, uiMainDataGridView, uiMainToolStrip);
}
private void SelectItem()
{
if (!IsSelectedMode)
{
Edit();
return;
}
if (uiMainDataGridView.SelectedRows.Count <= 0) return;
if (uiMainDataGridView.SelectedRows[0].Cells["Id"].Value != null)
{
DialogResult = DialogResult.OK;
SelectedGroup = _groups.FirstOrDefault(g => g.Id == (int)(uiMainDataGridView.SelectedRows[0].Cells["Id"].Value));
}
}
private void uiGroupsDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
SelectItem();
}
private void uiAddToolStripButton_Click(object sender, EventArgs e)
{
ShowForm(false);
}
private void ShowForm(bool isEditMode)
{
int id = isEditMode ? (int)(uiMainDataGridView.SelectedRows[0].Cells["Id"].Value) : -1;
using (var f = new GroupAddForm(id))
{
f.StartPosition = FormStartPosition.Manual;
f.Location = new Point(Location.X, Location.Y);
if (f.ShowDialog() == DialogResult.OK)
{
RefreshInfo();
}
}
}
private void uiDeleteToolStripButton_Click(object sender, EventArgs e)
{
Delete();
}
private void Delete()
{
if (uiMainDataGridView.SelectedRows.Count <= 0) return;
if (uiMainDataGridView.SelectedRows[0].Cells["Id"].Value != null)
{
try
{
if(IsDeleteConfirm())
{
var selectedId = Convert.ToInt32(uiMainDataGridView.SelectedRows[0].Cells["Id"].Value);
DatabaseManager.DeleteGroupById(selectedId);
RefreshInfo();
}
}
catch (Exception)
{
MessageBox.Show("Данный кабинет используется в расписание, его невозможно удалить.", "Информация");
}
}
}
private bool IsDeleteConfirm()
{
return MessageBox.Show("Удалить группу и расписание для неё?", "Требуется подтверждение",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes;
}
private void uiSelectToolStripButton_Click(object sender, EventArgs e)
{
SelectItem();
}
private void uiMainDataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Delete)
{
Delete();
}
}
private void uiEditToolStripButton_Click(object sender, EventArgs e)
{
Edit();
}
private void Edit()
{
if (uiMainDataGridView.SelectedRows.Count > 0)
{
ShowForm(true);
}
}
}
}
|
c380729e57fc75ac75a23491391dc5f9870d5417
|
C#
|
AvetisyanHayk/dotnet.o2
|
/MyHobbies/Band.cs
| 3
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace MyHobbies
{
public class Band
{
public const int MIN_JAAR = 1900;
public int Jaar { get; set; }
public string Naam { get; set; }
public List<BandLid> BandLeden { get; set; }
public Band()
{
this.BandLeden = new List<BandLid>();
this.Jaar = MIN_JAAR;
}
public static int MaxJaar()
{
return DateTime.Now.Year;
}
public void AddLid(BandLid lid)
{
this.BandLeden.Add(lid);
}
public override string ToString()
{
return $"Band: {Naam}, Jaar: {Jaar}";
}
}
}
|
b492e6a3a123131cc8117d3ae6508d22562c369d
|
C#
|
simo897d/MoreKataEx
|
/MoreKataEx/TwoSum.cs
| 3.28125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace MoreKataEx
{
using NUnit.Framework;
using System;
using System.Linq;
public class TwoSumClass {
public static int[] TwoSum(int[] numbers, int target) {
for (int i = 0; i < numbers.Length; i++) {
for (int j = 1; j < numbers.Length; j++) {
if (numbers[i] + numbers[j] == target) {
return new int[] { i, j };
}
}
}
return null;
}
}
[TestFixture]
public class KataTests {
[Test]
public void BasicTests() {
Assert.AreEqual(new[] { 0, 2 }, TwoSumClass.TwoSum(new[] { 1, 2, 3 }, 4).OrderBy(a => a).ToArray());
Assert.AreEqual(new[] { 1, 2 }, TwoSumClass.TwoSum(new[] { 1234, 5678, 9012 }, 14690).OrderBy(a => a).ToArray());
Assert.AreEqual(new[] { 0, 1 }, TwoSumClass.TwoSum(new[] { 2, 2, 3 }, 4).OrderBy(a => a).ToArray());
}
}
}
|
3e6a87cdbab75847b6fe78376b88dd357c7a0eb4
|
C#
|
leewoody/buguva
|
/Studijos/OS/KernelPrimityves/Operacine sistema/Resources/VirtualMachineResource.cs
| 3.078125
| 3
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class VirtualMachineResource : ResourceElement
{
private string programName;
public string ProgramName
{
get
{
return programName;
}
set
{
programName = value;
}
}
private int _virtualMachineIndex = -1;
public int VirtualMachineIndex
{
get
{ return _virtualMachineIndex; }
set
{
_virtualMachineIndex = value;
}
}
public void setProgramName(String p_strProgramName)
{
programName = p_strProgramName;
}
public String getProgramName()
{
return programName;
}
public override bool HasName
{
get
{
return true;
}
}
public override string ToString()
{
var index = VirtualMachineIndex;
if (index >= 0)
{
return String.Format("VM {0}: {1}", VirtualMachineIndex, ProgramName);
}
else
{
return String.Format("Any VM with {0} name", (!String.IsNullOrEmpty(ProgramName)) ? ProgramName : "any");
}
}
}
}
|
ffb22d7a34039bcd20ef0b498293f16cd9766da9
|
C#
|
oscarslaterj/EjericicosCSharp_Part2
|
/EjerciciosCSharp2/Capitulo 7/Cap7_Ejercicio1.cs
| 3.484375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EjerciciosCSharp2.Capitulo_7
{
public class Cap7_Ejercicio1
{
public static void CalPromedio()
{
int num;
Console.WriteLine("Ingrese Numero de Calificaciones a calcular ");
num = int.Parse(Console.ReadLine());
int s = 0;
int[] cali = new int[num];
for (int i = 0; i < cali.Length; i++)
{
Console.WriteLine("Ingrese Calificacion de estudiante ");
cali[i] = int.Parse(Console.ReadLine());
}
for (int id = 0; id < cali.Length; id++)
{
Console.WriteLine("/n Calificacion {0}: {1}", id, cali[id]);
s += cali[id];
}
Console.WriteLine("Su suma es " + s);
Console.WriteLine("Promedio de calificacion es " + s / cali.Length);
Array.Sort(cali);
Console.WriteLine("Calificacion minima es: " + cali[0]);
Array.Reverse(cali);
Console.WriteLine("Calificacion maxima es: " + cali[0]);
Console.ReadKey();
}
}
}
|
cdc0df986d663b5e998336a836cc8e8cddd6923d
|
C#
|
baccka/ir-project
|
/ir-project/Stemmer.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Iveonik.Stemmers;
namespace ir_project
{
/// <summary>
/// A stemmer class that wraps around the StemmersNET package.
/// </summary>
public class Stemmer
{
EnglishStemmer stemmer = new EnglishStemmer();
public String stem(String term)
{
return stemmer.Stem(term);
}
}
}
|
b1c5a293c66ea95bf66c9d0e53b93982e3ec809e
|
C#
|
kardelw1409/SOA
|
/SOAProjects/CurriculumService/Services/EntityCrudService.cs
| 2.765625
| 3
|
using CurriculumService.Context;
using CurriculumService.Infrastructure;
using CurriculumService.Interfaces;
using CurriculumService.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace CurriculumService.Services
{
public class EntityCrudService<TEntity> : IEntityCrudService<TEntity>
where TEntity : Entity
{
private DbContext db;
protected IDbFactory DbFactory { get; private set; }
protected DbContext DbContext
{
get { return db ?? (db = DbFactory.Init()); }
}
public EntityCrudService(IDbFactory dbFactory)
{
DbFactory = dbFactory;
}
public async Task Create(TEntity entity)
{
DbContext.Set<TEntity>().Add(entity);
await DbContext.SaveChangesAsync();
}
public async Task<TEntity> Remove(int id)
{
/*var entityItem = DbContext.Set<TEntity>().Where(p => p.Id == entity.Id).FirstOrDefault();
if (entityItem != null)
{
DbContext.Set<TEntity>().Remove(entityItem);
await DbContext.SaveChangesAsync();
}*/
var entityItem = await FindById(id);
if (entityItem == null)
{
throw new NullReferenceException("Data not find");
}
DbContext.Set<TEntity>().Remove(entityItem);
await DbContext.SaveChangesAsync();
return entityItem;
}
public async Task<TEntity> FindById(int id)
{
return await DbContext.Set<TEntity>().FindAsync(id);
}
public async Task<IEnumerable<TEntity>> GetAll()
{
return await DbContext.Set<TEntity>().AsNoTracking().ToListAsync();
}
public async Task Update(TEntity entity)
{
var entityItem = await DbContext.Set<TEntity>().SingleOrDefaultAsync(p => p.Id == entity.Id);
if (entityItem != null)
{
DbContext.Entry(entityItem).CurrentValues.SetValues(entity);
await DbContext.SaveChangesAsync();
}
}
public async Task<IEnumerable<TEntity>> Get(Func<TEntity, bool> predicate)
{
return await QueryableExtensions.ToListAsync(DbContext.Set<TEntity>().Where(predicate).AsQueryable());
}
public void Dispose()
{
db.Dispose();
}
}
}
|
54a4c28873d1f77d570bebdbc5e6c055ea198966
|
C#
|
pettijohn/TaskSchedulerEngine
|
/src/ExponentialBackoffTask.cs
| 3.015625
| 3
|
/*
* Task Scheduler Engine
* Released under the BSD License
* https://github.com/pettijohn/TaskSchedulerEngine
*/
using System;
using System.Threading;
namespace TaskSchedulerEngine
{
/// <summary>
/// Exponential backoff retry of a task. Retry interval is baseRetrySeconds*(2^retryCount).
/// Passes through to execute IScheduledTask; if it fails, this task adds itself back to the scheduler runtime.
/// This does not handle or swallow exceptions - IScheduledTask must gracefully fail return false from OnScheduleRuleMatch.
/// </summary>
public class ExponentialBackoffTask : IScheduledTask
{
public ExponentialBackoffTask(Func<ScheduleRuleMatchEventArgs, CancellationToken, bool> callback, int maxAttempts, int baseRetryInteravalSeconds)
: this(new RetryableTaskArgs(new AnonymousScheduledTask(callback), maxAttempts, baseRetryInteravalSeconds))
{
}
public ExponentialBackoffTask(RetryableTaskArgs args)
{
_args = args;
}
private RetryableTaskArgs _args;
public bool OnScheduleRuleMatch(ScheduleRuleMatchEventArgs e, CancellationToken c)
{
//Factory pattern needs to create a new instance to manage the retry lifetime of this invocation
// If we didn't clone then future instances here would start from already having their retries "used up."
var retryInvocation = new RetryableTaskInvocation(_args.Clone());
return retryInvocation.OnScheduleRuleMatch(e, c);
}
}
}
|
93fece9fd56a0ccf3a43f9df920499ebc7dadc4b
|
C#
|
MohitSethi99/ProbabilityManager
|
/Assets/DailyBonusSystem/Scripts/BonusItem.cs
| 2.53125
| 3
|
using System;
using UnityEngine;
[Serializable]
public class BonusItem
{
public string name;
[Range(0,100)]
public int ProbabilityPercent;
public float Angle;
public float Percent => (float) ProbabilityPercent / 100;
public int CompareTo(object obj) => Percent.CompareTo(((BonusItem) obj).Percent);
}
|
03eb6b4354a23bfa7da51265709ad1267b1ae1ac
|
C#
|
EASJ2018F/wcf-student-SabreUrn
|
/StudentService/StudentService/Service1.svc.cs
| 2.875
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace StudentService {
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : IService1 {
private Dictionary<string, Student> _studentList = new Dictionary<string, Student>();
public void AddStudent(string name, string className, string room) {
Student student = new Student(name, className, room);
_studentList.Add(student.Name, student);
}
public void EditStudent(string name, string className, string room) {
Student student = new Student(name, className, room);
_studentList[name] = student;
}
public List<string> FindStudents(string name) {
List<string> student = new List<string>();
student.Add(_studentList[name].Name);
student.Add(_studentList[name].ClassName);
student.Add(_studentList[name].Room);
return student;
}
public List<List<string>> GetAllStudents() {
List<List<string>> list = new List<List<string>>();
foreach(KeyValuePair<string, Student> kvp in _studentList) {
list.Add(FindStudents(kvp.Key));
}
return list;
}
public void RemoveStudent(string name) {
_studentList.Remove(name);
}
}
}
|
1a6238e3b2e6ce5c6d095aa75755dc5d7f5c44e9
|
C#
|
okosodovictor/Sample-Asp.net-Web-API
|
/BEAssignment.Core/Managers/InvoiceManager.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BEAssignment.Core.Business;
using BEAssignment.Core.Interfaces.DataAccess;
using BEAssignment.Core.Interfaces.Managers;
namespace BEAssignment.Core.Managers
{
public class InvoiceManager : IInvoiceManager
{
private readonly IInvoiceRepository _repo;
public InvoiceManager(IInvoiceRepository repo)
{
_repo = repo;
}
public Operation<InvoiceModel> CreateInvoice(InvoiceModel model)
{
return Operation.Create(() =>
{
if (model == null) throw new Exception("No Data Received");
model.Validate().Throw();
var newInvoice = _repo.CreateInvoice(model);
return newInvoice;
});
}
public Operation<InvoiceModel[]> GetInvoiceByAddressId(int addressId)
{
return Operation.Create(() =>
{
return _repo.GetInvoiceByAddressId(addressId);
});
}
public Operation<InvoiceModel[]> GetInvoiceByCustomerId(int customerId)
{
return Operation.Create(() =>
{
return _repo.GetInvoicesByCustomerId(customerId);
});
}
public Operation<InvoiceModel[]> GetInvoiceByCustomerIdAndAddres(int customerId, int addressId)
{
return Operation.Create(() =>
{
return _repo.GetInvoiceByCustomerIdAndAddress(customerId, addressId);
});
}
public Operation<InvoiceModel[]> GetInvoiceByCustomerIdAndMonth(int customerId, int month)
{
return Operation.Create(() =>
{
return _repo.GetInvoiceByCustomerIdAndMonth(customerId, month);
});
}
public Operation<InvoiceModel[]> GetInvoiceByCustomerIdFilterAndMonth(int customerId, string filter, int month)
{
return Operation.Create(() =>
{
return _repo.GetInvoiceByCustomerIdFilterAndMonth(customerId, filter, month);
});
}
}
}
|
be8b0584baa362cde3307c46f1d5d2636fa21e33
|
C#
|
IgorNazaryok/C-base-classes
|
/Generic/Geniric 5/Geniric 5/Program.cs
| 3.453125
| 3
|
using System;
namespace Geniric_5
{
class Program
{
static void Main(string[] args)
{
MyCollection<Car> myList = new MyCollection<Car>();
myList.Add(new Car("AMG", "1993"));
myList.Add(new Car("Ford", "2001"));
myList.Add(new Car("Tesla", "2016"));
for (int i = 0; i < myList.Count; i++)
{
myList[i].print();
}
Console.WriteLine("Кол-во элементов: " + myList.Count);
}
}
}
|
4bcd087464cd295a42b7a7faace573788995b37a
|
C#
|
Aysenurugur/Multi_Layer_Architecture_Web_HR_Project
|
/Services/Services/FileService.cs
| 2.671875
| 3
|
using Core.AbstractUnitOfWork;
using Core.Entities;
using Core.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services.Services
{
public class FileService : IFileService
{
private readonly IUnitOfWork unitOfWork;
public FileService(IUnitOfWork _unitOfWork)
{
this.unitOfWork = _unitOfWork;
}
public async Task<File> CreateFileAsync(File newFile)
{
newFile.CreatedDate = DateTime.Now;
await unitOfWork.File.AddAsync(newFile);
await unitOfWork.CommitAsync();
return newFile;
}
public async Task<File> GetFileByIdAsync(Guid id)
{
return await unitOfWork.File.GetByIDAsync(id);
}
public async Task<IEnumerable<File>> GetAllFilesAsync()
{
return await unitOfWork.File.GetAllAsync();
}
public async Task UpdateFileAsync(File file)
{
unitOfWork.File.Update(file);
await unitOfWork.CommitAsync();
}
public async Task<IEnumerable<File>> GetUserFilesAsync(Guid userId)
{
List<File> files = unitOfWork.File.List(x => x.UserID == userId).ToList();
return await Task.FromResult(files);
}
}
}
|
743eab10b483248403a7bdb3c19f6e8964e55c88
|
C#
|
yuri4029/UWP-Samples
|
/UWPCallODataServiceDemo/ProductService/ProductService/Migrations/Configuration.cs
| 3.078125
| 3
|
namespace ProductService.Migrations
{
using Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<ProductService.Models.ProductServiceContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(ProductService.Models.ProductServiceContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
// New code
context.Products.AddOrUpdate(new Product[] {
new Product() { ID = 1, Name = "Hat", Price = 15, Category = "Apparel" },
new Product() { ID = 2, Name = "Socks", Price = 5, Category = "Apparel" },
new Product() { ID = 3, Name = "Scarf", Price = 12, Category = "Apparel" },
new Product() { ID = 4, Name = "Yo-yo", Price = 4.95M, Category = "Toys" },
new Product() { ID = 5, Name = "Puzzle", Price = 8, Category = "Toys" },
});
}
}
}
|
288b471d3e91e2d2c3356bce7a96750ccb950ca0
|
C#
|
Agilsaav/TFM
|
/tfm/Assets/Scripts/Gameplay/WaveObject.cs
| 2.515625
| 3
|
using System.Collections;
using WavesBehavior;
using UnityEngine;
//Class not used: Make appear an object when colliding with the main wave.
public class WaveObject : MonoBehaviour
{
MeshRenderer mesh;
bool active = false;
private void Awake()
{
mesh = GetComponent<MeshRenderer>();
}
private void OnTriggerEnter(Collider other)
{
if(other.tag == "Wave" && !active )
{
if(other.GetComponent<WaveBehavior>().GetMainWaveBool())
{
mesh.enabled = true;
active = true;
}
}
}
}
|
76f11871c81ea4563f3cfc73b6e8162c558cd9b2
|
C#
|
MartinCarrion/Team9Spotify
|
/Tic-Tac-Toe/Team9Tic/MainWindow.xaml.cs
| 2.78125
| 3
|
//Team 9
//Martin Carrion
//Tristan Osborn
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Team9Tic
{
public partial class MainWindow : Window
{
Symbol[] Type = new Symbol[9];
bool Turns=false;
bool End=false;
public MainWindow()
{
InitializeComponent();
MessageBox.Show("Game of Tic-Tac-Toe");
Game();
}
private void BtnStart_Click(object sender, RoutedEventArgs e)
{
}
public void Game()
{
MessageBox.Show(" (X) Turn ");
Turns = true;
for (int i = 0; i < Type.Length; i++)
{
Type[i] = Symbol.NoSpace;
}
End = false;
RowsandColumns.Children.Cast<Button>().ToList().ForEach(button =>
{
button.Content = "";
});
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
var column = Grid.GetColumn(button);//Helps Place buttons
var row = Grid.GetRow(button);//Helps Place Buttons
var both = column + (row * 3);//equation that helps solidify buttons
if (End)
{
MessageBox.Show("Game has ended");
Game();
return;
}
if (Type[both] != Symbol.NoSpace)
{
return;
}
if (Turns)
{
Type[both] = Symbol.Cross;
button.Content = "X";
button.Foreground = Brushes.Purple;
MessageBox.Show(" (O) Turn ");
}
else
{
Type[both] = Symbol.Circle;
button.Content = "O";
button.Foreground = Brushes.Red;
MessageBox.Show(" (X) Turn ");
}
if (!Turns)
{
button.Foreground = Brushes.Yellow;
}
Turns ^= true;//switch players
Check();//Goes to Check method
}
public void Check()
{
var Row0 = Type[0] & Type[1] & Type[2];
var Row1 = Type[3] & Type[4] & Type[5];
var Row2 = Type[6] & Type[7] & Type[8];
var Col0 = Type[0] & Type[3] & Type[6];
var Col1 = Type[1] & Type[4] & Type[7];
var Col2 = Type[2] & Type[5] & Type[8];
var Dag1 = Type[0] & Type[4] & Type[8];
var Dag2 = Type[2] & Type[4] & Type[6];
var Tie = !Type.Any(t => t == Symbol.NoSpace);
if (Type[0] != Symbol.NoSpace && (Row0) == Type[0])//Select units in box. zig zag style
{
MessageBox.Show("Top Row !");
End = true;
}
else if (Type[3] != Symbol.NoSpace && (Row1) == Type[3])
{
MessageBox.Show("Middle Row !");
End = true;
}
else if (Type[6] != Symbol.NoSpace && (Row2) == Type[6])
{
MessageBox.Show("Last Row !");
End = true;
}
else if (Type[0] != Symbol.NoSpace && (Col0) == Type[0])
{
MessageBox.Show("Left Column !");
End = true;
}
else if (Type[1] != Symbol.NoSpace && (Col1) == Type[1])
{
MessageBox.Show("Middle Column !");
End = true;
}
else if (Type[2] != Symbol.NoSpace && (Col2) == Type[2])
{
MessageBox.Show("RIght Column !");
End = true;
}
else if (Type[0] != Symbol.NoSpace && (Dag1) == Type[0])
{
MessageBox.Show("Diagonal !");
End = true;
}
else if (Type[2] != Symbol.NoSpace && (Dag2) == Type[2])
{
MessageBox.Show("Diagonal !");
End = true;
}
else if (Tie)
{
End = true;
MessageBox.Show("TIE");
}
}
private void BtnStart_Click_1(object sender, RoutedEventArgs e)
{
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
}
}
|
c1066ee64c35fd644a1da77168634f1823e2cbcb
|
C#
|
v5100v5100/GVmakerForWin
|
/Script/Interpreter/LavApp.cs
| 3.09375
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Script.Interpreter
{
public class LavApp
{
private sbyte[] appData;
private int offset;
/// <summary>
/// 通过一个输入流创建一个LavApp对象
/// </summary>
/// <param name="inputStream">一个输入流</param>
/// <returns>一个LavApp对象</returns>
public static LavApp createLavApp(FileStream inputStream)
{
return new DefaultLavApp(inputStream);
}
/// <summary>
/// 通过一个lav程序数据来创建一个LavApp<p>
/// 注意,LavApp内部使用的就是该数组,类创建后不能从外部修改这个数组
/// </summary>
/// <param name="data"></param>
protected LavApp(sbyte[] data)
{
this.appData = data;
verifyData();
}
/// <summary>
/// lav程序数据大小(字节数)
/// </summary>
/// <returns>size 这个lav程序数据的总大小,含文件头</returns>
public int size()
{
return appData.Length;
}
/// <summary>
/// 在pointer处读取一字节数据,并使pointer加一<p>
/// 注意,这里返回值是char类型,对应lav的char类型,因为lav的char类型是无符号的.
/// </summary>
/// <returns></returns>
public UInt16 getChar()
{
return (UInt16) (appData[offset++] & 0xff);
}
/// <summary>
/// 从app中读取两字节数据,对应lav中的int类型
/// </summary>
/// <returns></returns>
public UInt16 getInt()
{
UInt16 s;
s = (UInt16)(appData[offset++] & 0xff);
//s |= (appData[offset++] & 0xff) << 8;
s |= (UInt16) ((appData[offset++] & 0xff) << 8);
return s;
}
/// <summary>
/// 从app中读取三字节数据(无符号),对应lav中文件指针数据
/// </summary>
/// <returns></returns>
public int getAddr()
{
int addr;
addr = appData[offset++] & 0xff;
addr |= (appData[offset++] & 0xff) << 8;
addr |= (appData[offset++] & 0xff) << 16;
return addr;
}
/// <summary>
/// 从app中读取四字节数据,对应lav中的long类型
/// </summary>
/// <returns></returns>
public int getLong()
{
int i;
i = appData[offset++] & 0xff;
i |= (appData[offset++] & 0xff) << 8;
i |= (appData[offset++] & 0xff) << 16;
i |= (appData[offset++] & 0xff) << 24;
return i;
}
/// <summary>
/// 得到当前数据偏移量
/// </summary>
/// <returns>下次读取时的位置</returns>
public int getOffset()
{
return offset;
}
/// <summary>
/// 设置读取偏移量
/// </summary>
/// <param name="pos">偏移量,下次读取数据时开始位置</param>
public void setOffset(int pos)
{
offset = pos;
}
/// <summary>
/// 检查数据格式并设置相应参数
/// data 一个lavApp数据
/// </summary>
private void verifyData()
{
if (appData.Length <= 16)
{
//throw new IllegalArgumentException("不是有效的LAV文件!");
}
if (appData[0] != 0x4c || appData[1] != 0x41 || appData[2] != 0x56)
{
//throw new IllegalArgumentException("不是有效的LAV文件!");
}
offset = 16;
}
}
}
|
4dc5c2661111c1c5b2436aeef01135b8087cda6e
|
C#
|
ltarne/Game-of-Goofs
|
/Game_of_Goofs/Assets/Scripts/CameraController.cs
| 2.640625
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour {
//--------------------------------------------------------------
//Primary camera rotation
[SerializeField]
Vector3 m_PrimaryRotation = new Vector3(50,0,0);
//Secondary camera rotation
[SerializeField]
Vector3 m_SecondaryRotation = new Vector3(-50, 0, 180);
//The speed of the rotation
[SerializeField]
float m_FlipSpeed = 10.0f;
//The time threshold to trigger the flip
[SerializeField]
float m_FlipTime = 5.0f;
//---------------------------------------------------------------
//bool m_Flip = false;
Vector3 m_CurrentRotation;
//---------------------------------------------------------------
// Use this for initialization
void Start () {
transform.rotation = Quaternion.Euler(m_PrimaryRotation);
m_CurrentRotation = m_PrimaryRotation;
}
// Update is called once per frame
void Update () {
Vector3 currentRotation = transform.rotation.eulerAngles;
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(m_CurrentRotation), m_FlipSpeed * Time.deltaTime);
//if (Time.time > m_FlipTime)
//{
// m_Flip = true;
//}
////Flip upside down
// if (m_Flip)
// {
// }
// //Flippin right way up
// else if (!m_Flip)
// {
// transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.Euler(m_PrimaryRotation), m_FlipSpeed * Time.deltaTime);
// }
}
public void Flip()
{
m_CurrentRotation = (m_CurrentRotation == m_PrimaryRotation) ? m_SecondaryRotation : m_PrimaryRotation;
}
}
|
798c7f5d6a247562bf0cd1ad2667956bd45e6599
|
C#
|
RonaldHordijk/DemoSquared
|
/DemoSquared.Utils/ModelQuery.cs
| 2.84375
| 3
|
using DemoSquared.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoSquared.Utils
{
// helper functions for getting infromation out the gbxml data structure
internal static class ModelQuery
{
public static Campus GetCampusFromModel(gbXML model)
{
if (model is null)
return null;
foreach (var item in model.Items)
{
if (item is Campus)
{
return item as Campus;
}
}
return null;
}
public static Building GetBuildingFromCampus(Campus campus)
{
if (campus is null)
return null;
foreach (var item in campus.Items)
{
if (item is Building)
{
return item as Building;
}
}
return null;
}
public static IEnumerable<Model.Space> GetSpacesFromBuilding(Building building)
{
if (building is null)
yield break;
foreach (var item in building.Items)
{
if (item is Model.Space)
{
yield return item as Model.Space;
}
}
}
public static ShellGeometry GetShellGeometryFromSpace(Model.Space space)
{
if (space is null)
return null;
foreach (var spaceItem in space.Items)
{
if (spaceItem is ShellGeometry)
{
return spaceItem as ShellGeometry;
}
}
return null;
}
public static ClosedShell GetClosedShellFromShellGeometry(ShellGeometry shellGeometry)
{
if (shellGeometry is null)
return null;
foreach (var item in shellGeometry.Items)
{
if (item is ClosedShell)
{
return item as ClosedShell;
}
}
return null;
}
public static string GetSpaceName(Model.Space space)
{
if (space is null)
return null;
foreach (var spaceItem in space.Items)
{
if (spaceItem is string)
{
return spaceItem as string;
}
}
return null;
}
}
}
|
8c91e3172d5b3fcf016e4ed6f192f9b6365d28b1
|
C#
|
Cmd-Robotic/GIK2F7-Laboration1-RobertHysingBerg
|
/Program.cs
| 3.59375
| 4
|
using System;
namespace Laboration1
{
class Program
{
static void Main(string[] args)
{ ///I might've skipped commenting for most of the main program, oh well I suppose that's fine for now...
mainUI();
}
static void mainUI()
{ ///Main user interface segment where our prospective shaper selects a shape
bool loopin = true;
string rawInput;
int input;
bool parsed;
Console.WriteLine("Hello and welcome to the shapezone!");
while (loopin)
{
Console.WriteLine("What shape would you like to use today, shaper?");
Console.WriteLine("1. Circle");
Console.WriteLine("2. Rectangle");
Console.WriteLine("3. Triangle");
Console.WriteLine("10. Exit program");
rawInput = Console.ReadLine();
parsed = Int32.TryParse(rawInput, out input);
if (parsed && input != 10)
{
shapeSelect(input);
}
else if (parsed && input == 10)
{
loopin = false;
Console.WriteLine("Allright, press enter when you're ready to exit the program. See you around shaper!");
Console.ReadLine();
}
else
{
Console.WriteLine("Couldn't quite catch what you said, try again!");
}
}
}
static void shapeSelect(int userChoice)
{ ///This segment only shoves the program along to the correct shape
switch (userChoice)
{
case 1:
circleShaper();
break;
case 2:
rectangleShaper();
break;
case 3:
triangleShaper();
break;
default:
Console.WriteLine("Sorry shaper, I don't know what shape you're trying to use, try again!");
break;
}
}
static void circleShaper()
{ ///Constructs a new Circle
Circle shape = new Circle();
Console.WriteLine("Allright, a circle has been randomly generated.");
shapersInfo(shape);
}
static void rectangleShaper()
{ ///Constructs a new Rectangle
Rectangle shape = new Rectangle();
Console.WriteLine("Allright, a rectangle has been randomly generated.");
shapersInfo(shape);
}
static void triangleShaper()
{ ///Constructs a new Triangle
Triangle shape = new Triangle();
Console.WriteLine("Allright, a triangle has been randomly generated.");
shapersInfo(shape);
}
static void shapersInfo(Circle shape)
{ ///This is where the user gets some info about the shape, I almost went ahead and made it so the user can modify the shapes but uh, that's out of scope of this lab if I've understood it correctly
///There are three different functions, two of them being overload functions, one for each shape and they look mostly the same with some minor differences in the Console.WriteLine()s
bool loopin = true;
bool parsed;
string rawInput;
int input;
string question = "So what do you want to know about the shape?";
while (loopin)
{
Console.WriteLine(question);
question = "Anything else you want to know about the shape?";
Console.WriteLine("1. Get all the info about it");
Console.WriteLine("2. Get its area");
Console.WriteLine("3. Get its circumference");
Console.WriteLine("10. Go back to shape select");
rawInput = Console.ReadLine();
parsed = Int32.TryParse(rawInput, out input);
if (parsed && input != 10)
{
switch (input)
{
case 1:
(string, float[], float[]) shapeInfo = shape.getInfo();
Console.WriteLine("This is a {0} with a radius of {1} and a diameter of {2}. The area of this circle is around {3} and the circumference is {4}.",
shapeInfo.Item1, shapeInfo.Item2[0], shapeInfo.Item2[1], shapeInfo.Item3[0], shapeInfo.Item3[1]);
break;
case 2:
Console.WriteLine("This circle has an area of {0}", shape.getArea());
break;
case 3:
Console.WriteLine("This circle has a circumference of {0}", shape.getCircumference());
break;
default:
Console.WriteLine("What was that input shaper? I don't think it was an option... please try again.");
break;
}
}
else if (parsed && input == 10)
{
loopin = false;
Console.WriteLine("Allright, press enter when you're ready to go back to shape select shaper.");
Console.ReadLine();
}
else
{
Console.WriteLine("Couldn't quite catch what you said, try again!");
}
}
}
static void shapersInfo(Rectangle shape)
{ ///This is where the user gets some info about the shape, I almost went ahead and made it so the user can modify the shapes but uh, that's out of scope of this lab if I've understood it correctly
///There are three different functions, two of them being overload functions, one for each shape and they look mostly the same with some minor differences in the Console.WriteLine()s
bool loopin = true;
bool parsed;
string rawInput;
int input;
string question = "So what do you want to know about the shape?";
while (loopin)
{
Console.WriteLine(question);
question = "Anything else you want to know about the shape?";
Console.WriteLine("1. Get all the info about it");
Console.WriteLine("2. Get its area");
Console.WriteLine("3. Get its circumference");
Console.WriteLine("10. Go back to shape select");
rawInput = Console.ReadLine();
parsed = Int32.TryParse(rawInput, out input);
if (parsed && input != 10)
{
switch (input)
{
case 1:
(string, float[], float[]) shapeInfo = shape.getInfo();
Console.WriteLine("This is a {0} with the length of the sides being {1}, {2}, {3} and {4}. The area of this rectangle is around {5} and the circumference is {6}.",
shapeInfo.Item1, shapeInfo.Item2[0], shapeInfo.Item2[1], shapeInfo.Item2[2], shapeInfo.Item2[3], shapeInfo.Item3[0], shapeInfo.Item3[1]);
break;
case 2:
Console.WriteLine("This rectangle has an area of {0}", shape.getArea());
break;
case 3:
Console.WriteLine("This rectangle has a circumference of {0}", shape.getCircumference());
break;
default:
Console.WriteLine("What was that input shaper? I don't think it was an option... please try again.");
break;
}
}
else if (parsed && input == 10)
{
loopin = false;
Console.WriteLine("Allright, press enter when you're ready to go back to shape select shaper.");
Console.ReadLine();
}
else
{
Console.WriteLine("Couldn't quite catch what you said, try again!");
}
}
}
static void shapersInfo(Triangle shape)
{ ///This is where the user gets some info about the shape, I almost went ahead and made it so the user can modify the shapes but uh, that's out of scope of this lab if I've understood it correctly
///There are three different functions, two of them being overload functions, one for each shape and they look mostly the same with some minor differences in the Console.WriteLine()s
bool loopin = true;
bool parsed;
string rawInput;
int input;
string question = "So what do you want to know about the shape?";
while (loopin)
{
Console.WriteLine(question);
question = "Anything else you want to know about the shape?";
Console.WriteLine("1. Get all the info about it");
Console.WriteLine("2. Get its area");
Console.WriteLine("3. Get its circumference");
Console.WriteLine("10. Go back to shape select");
rawInput = Console.ReadLine();
parsed = Int32.TryParse(rawInput, out input);
if (parsed && input != 10)
{
switch (input)
{
case 1:
(string, float[], float[]) shapeInfo = shape.getInfo();
Console.WriteLine("This is a {0} with each side being {1}, {2} and {3} long respectively. The area of this triangle is around {4} and the circumference is {5}.",
shapeInfo.Item1, shapeInfo.Item2[0], shapeInfo.Item2[1], shapeInfo.Item2[2], shapeInfo.Item3[0], shapeInfo.Item3[1]);
break;
case 2:
Console.WriteLine("This triangle has an area of {0}", shape.getArea());
break;
case 3:
Console.WriteLine("This triangle has a circumference of {0}", shape.getCircumference());
break;
default:
Console.WriteLine("What was that input shaper? I don't think it was an option... please try again.");
break;
}
}
else if (parsed && input == 10)
{
loopin = false;
Console.WriteLine("Allright, press enter when you're ready to go back to shape select shaper.");
Console.ReadLine();
}
else
{
Console.WriteLine("Couldn't quite catch what you said, try again!");
}
}
}
}
}
|
0cf0bbbab428651963f363da311e6812cfd1e0e3
|
C#
|
NBorba/Aulas_Xamarin
|
/Program.cs
| 3.59375
| 4
|
using System;
namespace PrimeiroProjeto
{
class MainClass
{
private const double PI = 3.14;
public static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Digite abaixo o exercício desejado: ");
try
{
int idExercicio = 0;
if (int.TryParse(Console.ReadLine(), out idExercicio))
{
ResolverExercicio(idExercicio);
}
else
{
Console.WriteLine("Digite um número válido!");
}
}
catch (Exception ex)
{
Console.WriteLine("Erro: " + ex.Message.Trim());
}
}
}
private static void ResolverExercicio(int idExercicio)
{
switch (idExercicio)
{
case 1:
ExercicioUm();
break;
case 2:
ExercicioDois();
break;
case 3:
ExercicioTres();
break;
case 4:
ExercicioQuatro();
break;
case 5:
ExercicioCinco();
break;
case 6:
ExercicioSeis();
break;
default:
Console.WriteLine("Nenhum exercício com este número encontrado!");
break;
}
}
#region Resolução Ex. 1
private static void ExercicioUm()
{
int qtdNotas = 4;
double[] notas = new double[qtdNotas];
Console.Clear();
Console.WriteLine("--- Exercício 1 ---");
Console.WriteLine("Digite " + qtdNotas + " notas para calcular a média");
for (int i = 0; i < qtdNotas; i++)
{
Console.WriteLine("Nota " + (i + 1) + ": ");
while (!double.TryParse(Console.ReadLine(), out notas[i]))
{
Console.WriteLine("Digite uma nota válida para a nota " + (i + 1) + "!");
}
}
Console.Clear();
double mediaNotas = 0;
for (int i = 0; i < qtdNotas; i++)
{
mediaNotas += notas[i];
}
mediaNotas = mediaNotas / qtdNotas;
Console.WriteLine("Média das " + qtdNotas + " notas: " + mediaNotas);
}
#endregion
#region Resolução Ex. 2
private static void ExercicioDois()
{
Console.Clear();
Console.WriteLine("--- Exercício 2 ---");
Console.WriteLine("Converter Fahrenheit para Celsius: ");
double temperaturaFahrenheit = 0;
while (!double.TryParse(Console.ReadLine(), out temperaturaFahrenheit))
{
Console.WriteLine("Digite uma temperatura válida!");
}
double temperaturaCelsius = (temperaturaFahrenheit - 32) / 1.8;
Console.WriteLine("Temperatura " + Math.Round(temperaturaFahrenheit, 2) + "F igual a " + Math.Round(temperaturaCelsius, 2) + "C");
}
#endregion
#region Resolução Ex. 3
private static void ExercicioTres()
{
Console.Clear();
Console.WriteLine("--- Exercício 3 ---");
Console.WriteLine("Forneça o raio da esfera e descubra sua área e volume: ");
double raio = 0;
while (!double.TryParse(Console.ReadLine(), out raio))
{
Console.WriteLine("Digite um valor válido para o raio!");
}
double area = 4 * PI * Math.Pow(raio, 2);
double volume = (4 * PI * Math.Pow(raio, 3)) / 3;
Console.WriteLine("Raio: " + Math.Round(raio, 2));
Console.WriteLine("Área: " + Math.Round(area, 2));
Console.WriteLine("Volume: " + Math.Round(volume,2));
}
#endregion
#region Resolução Ex. 4
private static void ExercicioQuatro()
{
Console.Clear();
Console.WriteLine("--- Exercício 4 ---");
Console.WriteLine("Digite um número: ");
int numero = 0;
while (!int.TryParse(Console.ReadLine(), out numero))
{
Console.WriteLine("Digite um número válido!");
}
bool multiploDeCinco = numero % 5 == 0;
bool positivo = numero > 0;
if (multiploDeCinco && positivo)
{
Console.WriteLine("OK");
}
else if (multiploDeCinco || positivo)
{
Console.WriteLine("PARCIAL");
}
else
{
Console.WriteLine("INCORRETO");
}
}
#endregion
#region ExercicioCinco
private static void ExercicioCinco()
{
Console.Clear();
Console.WriteLine("--- Exercício 5 ---");
Console.WriteLine("Digite um número inteiro para calcular Fibonacci: ");
int numero = 0;
while (!int.TryParse(Console.ReadLine(), out numero))
{
Console.WriteLine("Digite um número válido!");
}
int[] numerosFibonacci = new int[numero];
for (int i = 0; i < numero; i++)
{
if (i <= 1)
{
numerosFibonacci[i] = numero;
}
else
{
numerosFibonacci[i] = Fibonacci(numerosFibonacci[i - 1], numerosFibonacci[i - 2]);
}
}
Console.WriteLine("Fibonacci de " + numero);
for (int i = 0; i < numero; i++)
{
Console.WriteLine(numerosFibonacci[i]);
}
}
private static int Fibonacci(int numero, int numeroAnterior)
{
return numero + numeroAnterior;
}
#endregion
#region Resolução Ex. 6
private static void ExercicioSeis()
{
const double PRECO_LATA = 50;
const double LITROS_LATA = 5;
const double LITRO_PINTA_M2 = 3;
double alturaTanque = 0;
double raioTanque = 0;
Console.Clear();
Console.WriteLine("--- Exercício 6 ---");
Console.WriteLine("Digite os dados do tanque de combustível para calcular o custo da tinta: ");
Console.WriteLine("Digite a altura do tanque: ");
while (!double.TryParse(Console.ReadLine(), out alturaTanque))
{
Console.WriteLine("Digite uma altura válida!");
}
Console.WriteLine("Digite o raio do tanque: ");
while (!double.TryParse(Console.ReadLine(), out raioTanque))
{
Console.WriteLine("Digite um raio válido!");
}
double comprimento = 2 * PI * raioTanque;
double areaBase = PI * Math.Pow(raioTanque, 2);
double areaLateral = alturaTanque * comprimento;
double areaCilindro = areaBase + areaLateral;
double qtdLitrosTotais = (areaCilindro / LITRO_PINTA_M2);
double qtdLatasNecessarias = qtdLitrosTotais / LITROS_LATA;
double precoTotal = qtdLatasNecessarias * PRECO_LATA;
string mensagem = "Irá custar R$" + Math.Round(precoTotal, 2) + " para comprar " + Math.Round(qtdLatasNecessarias, 2)
+ " latas que iram pintar " + areaCilindro + " metros quadrados do cilindro.";
Console.WriteLine(mensagem);
}
#endregion
}
}
|
8cb5decadacc6e0b5d0fb4937c6cb3792554b33d
|
C#
|
thegamefactory/the-world-factory-unity
|
/Assets/Scripts/Core/Base/Pathfinding/IPathFinder.cs
| 2.578125
| 3
|
namespace TWF
{
/// <summary>
/// A path finder interface.
/// Finds paths between the origin and the destinaton, specifying a maximum past cost.
/// The maximum past cost is only meaningful in the context of the connection cost between nodes in the searched graph.
/// The returned path must be constructed externally.
/// </summary>
public interface IPathFinder<TNode>
{
bool FindPath(IGraph<TNode> graph, TNode origin, TNode destination, int maxCost, ref Path<TNode> path);
}
}
|
43fca5303a2b56717e87bbbf87fe074aa1d4cfaf
|
C#
|
baichuan72f/UITools
|
/UITools/Assets/Singleton/SingletonPropertyExample.cs
| 2.53125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HFrameExample
{
public class SingletonPropertyExample : MonoBehaviour
{
public class TestSingletonPropertyExample : ISingleton
{
private TestSingletonPropertyExample()
{
}
public static TestSingletonPropertyExample Instance
{
get { return SingletonProperty<TestSingletonPropertyExample>.Instace; }
}
public void InitSingleton()
{
}
}
// Start is called before the first frame update
void Start()
{
TestSingletonPropertyExample instance1 = TestSingletonPropertyExample.Instance;
TestSingletonPropertyExample instance2 = TestSingletonPropertyExample.Instance;
Debug.Log(instance1.GetHashCode() == instance2.GetHashCode());
}
// Update is called once per frame
void Update()
{
}
}
}
|
dac3f91593222b61ca138c2d1afd4dbf84c4467a
|
C#
|
MaxDac/gilded-rose-csharp
|
/csharpcore.tests/BackstagePassesTests.cs
| 2.65625
| 3
|
using System.Collections.Generic;
using Xunit;
namespace csharpcore
{
public class BackstagePassesTests
{
private const string BACKSTAGE_PASSES_NAME = "Backstage passes to a TAFKAL80ETC concert";
[Fact]
public void BackstagePassesIncreaseValueBeforeTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 15, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(11, app.GetItems()[0].Quality);
Assert.Equal(14, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesIncreaseValueTwiceTenDaysBeforeTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 10, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(12, app.GetItems()[0].Quality);
Assert.Equal(9, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesIncreaseValueTwiceNineDaysBeforeTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 9, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(12, app.GetItems()[0].Quality);
Assert.Equal(8, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesIncreaseValueThriceFiveDaysBeforeTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 5, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(13, app.GetItems()[0].Quality);
Assert.Equal(4, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesIncreaseValueThriceFourDaysBeforeTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 4, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(13, app.GetItems()[0].Quality);
Assert.Equal(3, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesLoseValueAfterTheConcert()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 0, Quality = 10 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(0, app.GetItems()[0].Quality);
Assert.Equal(-1, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesQualityDoesNotIncreaseAfterFifty()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 11, Quality = 50 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(50, app.GetItems()[0].Quality);
Assert.Equal(10, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesQualityDoesNotIncreaseAfterFiftyBeforeTenDays()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 10, Quality = 50 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(50, app.GetItems()[0].Quality);
Assert.Equal(9, app.GetItems()[0].SellIn);
}
[Fact]
public void BackstagePassesQualityDoesNotIncreaseAfterFiftyBeforeFiveDays()
{
var app = new GildedRose(
new List<Item> { new Item { Name = BACKSTAGE_PASSES_NAME, SellIn = 5, Quality = 50 } });
app.UpdateQuality();
Assert.Equal(BACKSTAGE_PASSES_NAME, app.GetItems()[0].Name);
Assert.Equal(50, app.GetItems()[0].Quality);
Assert.Equal(4, app.GetItems()[0].SellIn);
}
}
}
|
aef4559f98023700bd3b61ec451541b0146463cf
|
C#
|
owenbai101/adproject
|
/Team4_Ad/logic/Business.cs
| 2.578125
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using Team4_Ad.WCF;
using System.Web.Security;
using System.Collections;
namespace Team4_Ad
{
public class Business
{
public static string Finditemidbyname(string name)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.ItemLists.Where(x => x.Description.Contains(name)).Select(y => y.ItemId).First();
}
}
public static decimal Findavgitempricebyid(string itemId)
{
using (LastADEntities ctx = new LastADEntities())
{
var t = ctx.ItemSuppliers.Where(x => x.ItemId == itemId).Select(y => y.Price).ToList();
decimal avgprice = 0;
for (int i = 0; i < t.Count; i++)
{
avgprice += (Decimal)(t[i]);
}
return avgprice / t.Count;
}
}
public static List<RequDetail> RetriveReqOutstanding(int reqID)
{
using (LastADEntities ctx = new LastADEntities())
{
// retrive the requisition with outstanding amount
return ctx.RequDetails.Where(x => x.RequDetailId == reqID).Where(y => y.OutstandingQuantity != 0).ToList<RequDetail>();
}
}
public static List<Requisition> ListRequsitionWithPendingtoCollection()
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Requisitions.Where(x => x.Status.Equals("Waiting for Collection")).ToList<Requisition>();
}
}
public static List<RequDetail> GetOutStandingRequsitionDetail()
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.RequDetails.Where(x => x.OutstandingQuantity != 0 && x.Requisition.Status.Equals("Waiting for Collection")).ToList<RequDetail>();
}
}
public static List<RequDetail> GetOutStandingRequsitionDetailForSelectedItem(ArrayList list)
{
using (LastADEntities ctx = new LastADEntities())
{
List<RequDetail> Relist = new List<RequDetail>();
foreach (int i in list)
{
List<RequDetail> detaillist = ctx.RequDetails.Where(x => x.Requisition.RequId == i).ToList();
foreach (RequDetail dd in detaillist)
{
Relist.Add(dd);
}
}
return Relist.ToList<RequDetail>();
}
}
public static List<Requisition> ListRequsitionFrombystatus(string status)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Requisitions.Where(x => x.Status.Equals(status)).ToList<Requisition>();
}
}
public static List<ItemList> FindItemByID(string itemID)
{
using (LastADEntities ctx = new LastADEntities())
{
//List<ItemList> ll = new List<ItemList>();
//ItemList i= ctx.ItemLists.Where(x => x.ItemId == itemID).First();
//ll.Add(i);
//return ll;
return ctx.ItemLists.Where(x => x.ItemId == itemID).ToList<ItemList>();
}
}
public static ItemList FinditemobjByID(string itemId)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.ItemLists.Where(x => x.ItemId == itemId).First();
}
}
public static int GetTotalQtyNeeded(String itemid)
{
List<RequDetail> templistDetails = GetOutStandingRequsitionDetail();
int tqNeeded = 0;
foreach (var item in templistDetails)
{
if (item.ItemId == itemid )
{
tqNeeded += Convert.ToInt32(item.OutstandingQuantity);
}
}
return tqNeeded;
}
public static int GetTotalQtyNeededForSelectedItem(String itemid, ArrayList list)
{
List<RequDetail> templistDetails = GetOutStandingRequsitionDetailForSelectedItem(list);
int tqNeeded = 0;
foreach (var item in templistDetails)
{
if (item.ItemId == itemid)
{
tqNeeded += Convert.ToInt32(item.OutstandingQuantity);
}
}
return tqNeeded;
}
public static List<ItemCategory> Listcategory()
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.ItemCategories.ToList<ItemCategory>();
}
}
public static List<ItemList> GetitemListbyCatname(string Categoryname)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.ItemLists.Where(p => p.ItemCategory.CategoryName == Categoryname).ToList<ItemList>();
}
}
public static List<RequDetail> GetRequDEtialbyID(int requisitionid)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.RequDetails.Where(p => p.RequId == requisitionid).ToList<RequDetail>();
}
}
public static void ConfirmRequsition(int requsitionid, string reason,string signby)
{
using (LastADEntities ctx = new LastADEntities())
{
Requisition requsition = ctx.Requisitions.Where(x => x.RequId == requsitionid).First<Requisition>();
requsition.Status = "Waiting for Collection";
requsition.SignDate = DateTime.Now;
requsition.SignBy = signby;
requsition.Note = reason;
ctx.SaveChanges();
}
}
public static void RejectRequisition(int requisitionid, string reason, string signby)
{
using (LastADEntities ctx = new LastADEntities())
{
Requisition requsition = ctx.Requisitions.Where(x => x.RequId == requisitionid).First<Requisition>();
requsition.Status = "Rejected";
requsition.SignDate = DateTime.Now;
requsition.SignBy = signby;
requsition.Note = reason;
List<RequDetail> reqdetail = ctx.RequDetails.Where(y => y.RequId == requisitionid).ToList();
foreach (RequDetail a in reqdetail)
{
a.OutstandingQuantity = 0;
}
ctx.SaveChanges();
}
}
public static ItemList GetitemListbyItemId(string ItemId)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.ItemLists.Where(p => p.ItemId == ItemId).First();
}
}
public static SmtpClient sendemail()
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential
("ADProjectTeam04@gmail.com",
"ADProjectTeam04!");
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
return client;
}
public static List<WCF_RequsitionJoinEmployee> ListRequisitionNotAprrove()
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Requisitions.Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee { Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).Where(x => x.status == "Pending Approval").ToList<WCF_RequsitionJoinEmployee>();
}
}
public static WCF_RequsitionJoinEmployee GetRequisitionbyid(int reqid)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Requisitions.Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee { Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).Where(x => x.Requid == reqid).First();
}
}
public static List<int> GetRequidPendingApprove()
{
using (LastADEntities ctx = new LastADEntities())
{
List<int> list = new List<int>();
foreach (WCF_RequsitionJoinEmployee r in ListRequisitionNotAprrove())
{
list.Add(r.Requid);
}
return list;
}
}
public static List<string> GetitemIdbyCatname(string Categoryname)
{
using (LastADEntities ctx = new LastADEntities())
{
List<string> list = new List<string>();
foreach (ItemList i in GetitemListbyCatname(Categoryname))
{
list.Add(i.ItemId);
}
return list;
}
}
public static List<string> GetRequisitionDetailid(int requid)
{
using (LastADEntities ctx = new LastADEntities())
{
List<string> list = new List<string>();
foreach (RequDetail i in GetRequDEtialbyID(requid))
{
list.Add(i.RequDetailId.ToString());
}
return list;
}
}
public static WCF_RequisitionDetail GetRequisitionDetailByRequisitionId(int RequisitionDetailId)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.RequDetails.Where(x => x.RequDetailId == RequisitionDetailId).Join(ctx.ItemLists, m => m.ItemId, f => f.ItemId, (m, f) =>
new WCF_RequisitionDetail { Requid = m.RequId.ToString(), itemid = m.ItemId, name = f.Description, quantity = m.RequestedQuantity.ToString(), OutstandingQuantity = m.OutstandingQuantity.ToString() }).First();
}
}
public static List<int> GetRequidWaitingForCollection()
{
using (LastADEntities ctx = new LastADEntities())
{
List<int> list = new List<int>();
foreach (Requisition r in ListRequsitionWithPendingtoCollection())
{
list.Add(r.RequId);
}
return list;
}
}
//public static void ChangeCollectionPoint(int id)
//{
// LastADEntities ctx = new LastADEntities();
// Department c = ctx.Departments.Where(x => x.CollectionPointId == id).First();
// c.CollectionPointId = id;
// ctx.SaveChanges();
//}
public static void ChangeCollectionPoint(int id, string dpcd)
{
LastADEntities ctx = new LastADEntities();
Department c = ctx.Departments.Where(x => x.DepartmentCode == dpcd).First();
c.CollectionPointId = id;
ctx.SaveChanges();
}
public static List<WCF_RequisitionDetailJoinItemList> RetrievalList()
{
LastADEntities ctx = new LastADEntities();
List<WCF_RequisitionDetailJoinItemList> list = ctx.RequDetails.Where(x => x.Requisition.Status.Equals("Waiting for Collection")).GroupBy(x => x.ItemId).
Select(y => (new { id = y.Key, quantity = y.Sum(x => x.OutstandingQuantity) }))
.Join(ctx.ItemLists, m => m.id, f => f.ItemId, (m, f) => new WCF_RequisitionDetailJoinItemList
{ itemid = m.id, itemname = f.Description, Quantity = m.quantity, uom = f.UOM, bin = f.Bin })
.OrderBy(x => x.bin).ToList();
foreach (WCF_RequisitionDetailJoinItemList w in list)
{
int quantityneed = Business.GetTotalQtyNeeded(w.itemid);
w.RetrievalQuantity = Business.GetTotalQtyNeeded(w.itemid).ToString();
int? Stock = ctx.ItemLists.Where(x => x.ItemId.Equals(w.itemid)).Select(x => x.Stock).First();
if (Stock > quantityneed)
{
w.RetrievalQuantity = quantityneed.ToString();
}
else
{
w.RetrievalQuantity = Stock.ToString();
}
}
return list;
}
public static List<WCF_RequisitionDetailJoinItemList> RetrievalListSimple(ArrayList requlist)
{
LastADEntities ctx = new LastADEntities();
List<WCF_RequisitionDetailJoinItemList> WCF_RequisitionDetailJoinItemList = new List<WCF_RequisitionDetailJoinItemList>();
List<RequDetail> itlist = new List<RequDetail>();
foreach (int id in requlist)
{
List<RequDetail> detaillist = ctx.RequDetails.Where(x => x.Requisition.RequId == id).ToList();
foreach(RequDetail dd in detaillist)
{
itlist.Add(dd);
}
}
List<WCF_RequisitionDetailJoinItemList> list =itlist. GroupBy(x => x.ItemId).
Select(y => (new { id = y.Key, quantity = y.Sum(x => x.OutstandingQuantity) }))
.Join(ctx.ItemLists, m => m.id, f => f.ItemId, (m, f) => new WCF_RequisitionDetailJoinItemList
{ itemid = m.id, itemname = f.Description, Quantity = m.quantity, uom = f.UOM, bin = f.Bin })
.OrderBy(x => x.bin).ToList();
return list;
}
public static List<Requisition> ListRequsitionWithWaitingForDelivery()
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Requisitions.Where(x => x.Status.Equals("Waiting for Delivery")).ToList<Requisition>();
}
}
public static List<int> GetRequidWaitingForDelivery()
{
using (LastADEntities ctx = new LastADEntities())
{
List<int> list = new List<int>();
foreach (Requisition r in ListRequsitionWithWaitingForDelivery())
{
list.Add(r.RequId);
}
return list;
}
}
public static String Confrimrequ(List<WCF_RequisitionDetail> WRDS)
{
//String WRDD= WRD.ToString();
//JArray array = (JArray)JsonConvert.DeserializeObject(WRDD);
//List<WCF_RequisitionDetail> WRDS = new List<WCF_RequisitionDetail>();
//foreach (JObject j in array)
//{
// WCF_RequisitionDetail w= j.ToObject<WCF_RequisitionDetail>();
// WRDS.Add(w);
//}
int requid = Convert.ToInt32(WRDS.First().Requid);
// int id = 13;
LastADEntities entities = new LastADEntities();
Requisition requ = entities.Requisitions.Where(x => x.RequId == requid).First();
List<RequDetail> details = requ.RequDetails.ToList();
int percentage = 0;
string ending = WRDS.ToString();
//String WCFitemid = "1";
try
{
// foreach (RequDetail detail in details)
for (int i = 0; i < WRDS.Count(); i++)
{
// entities.Entry(detail).State = System.Data.Entity.EntityState.Modified;
//WCFitemid = WRDS[i].itemid.ToString();
String WCFitemdesc = WRDS[i].name.ToString();
// ending = WCFitemid;
RequDetail wdetail = details.Where(x => x.ItemList.Description == WCFitemdesc).First();
wdetail.OutstandingQuantity = Convert.ToInt32(WRDS[i].OutstandingQuantity);
if (wdetail.OutstandingQuantity != 0)
percentage++;
else { }
if (percentage == 0)
{
requ.Status = "Completed";
requ.CollectionDate = DateTime.Now;
}
else
{
requ.Status = "Waiting for Collection";
}
entities.Entry(requ).State = System.Data.Entity.EntityState.Modified;
}
entities.SaveChanges();
ending = "execute successfully";
}
catch (Exception e)
{
ending = e.ToString();
}
return ending;
}
public static List<WCF_RequsitionJoinEmployee> ListRequsitionWithPendingtoCollectionWithDepartmentID(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Waiting for Collection") && x.Employee.Department.DepartmentCode.Equals(DpCode)).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{ Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static List<WCF_RequsitionJoinEmployee> ListRequsitionCompleteWithDepartmentID(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Completed") && x.Employee.Department.DepartmentCode.Equals(DpCode)).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{ Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static List<WCF_RequsitionJoinEmployee> ListRequsitionRejectedWithDepartmentID(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Rejected") && x.Employee.Department.DepartmentCode.Equals(DpCode)).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{ Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static List<WCF_RequsitionJoinEmployee> ListRequsitionPendingApprovalWithDepartmentID(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Pending Approval") && x.Employee.Department.DepartmentCode.Equals(DpCode)).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{ Requid = m.RequId, name = f.Name, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static List<WCF_RequsitionJoinEmployee> ListRequsitionWaitingForDeliveryWithDepartmentID(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Waiting For Delivery") && x.Employee.Department.DepartmentCode.Equals(DpCode)).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{
Requid = m.RequId,
name = f.Name,
SubmittedDate = m.RequestedDate.ToString(),
status = m.Status
}).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static List<WCF_RequsitionJoinEmployee> ListRequisitionWithPendingtoCollectionForClerk()
{
using (LastADEntities ctx = new LastADEntities())
{
List<WCF_RequsitionJoinEmployee> list = ctx.Requisitions.Where(x => x.Status.Equals("Waiting for Collection")).Join(ctx.Employees, m => m.EmployeeId, f => f.UserId, (m, f) => new WCF_RequsitionJoinEmployee
{ Requid = m.RequId, DepartmentCode = f.DepartmentCode, SubmittedDate = m.RequestedDate.ToString(), status = m.Status }).ToList<WCF_RequsitionJoinEmployee>();
return list;
}
}
public static String GetCollectionPointName(String DpCode)
{
using (LastADEntities ctx = new LastADEntities())
{
return ctx.Departments.Where(x => x.DepartmentCode.Equals(DpCode)).First().CollectionPoint.CollectionPointName.ToString();
}
}
}
}
|
3c374533af97dea999c66b2e07f52e9764150df6
|
C#
|
RuudHagens/Portfolio
|
/Semester 2/C# projects/IComparable_Student/IComparable_Student/Student.cs
| 3.578125
| 4
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IComparable_Student
{
class Student : IComparable<Student>
{
protected string name;
protected string address;
protected int number;
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public int Number
{
get { return number; }
set { number = value; }
}
public Student(string name, string address, int number)
{
this.name = name;
this.address = address;
this.number = number;
}
public override string ToString()
{
return String.Format("Name: {0} - Address: {1} - Studentnumber: {2}", name, address, number);
}
public int CompareTo(Student other)
{
//aflopend
if (this.Number < other.Number) return 1;
if (this.Number > other.Number) return -1;
else return 0;
}
}
}
|
de4621ee5a984667265a110b970af58c5249a587
|
C#
|
LonelyReaction/Bamss
|
/Communication/FTP/FTPClient.cs
| 2.765625
| 3
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Threading;
using System.IO;
using System.Net;
using BAMSS.Extensions;
namespace BAMSS.Communication.FTP
{
public class FTPClient
{
private string _serverName;
private string _directoryName;
public string ServerName
{
get { return this._serverName; }
private set { this._serverName = this.CutPathDelimiter(value); }
}
public string DirectoryName
{
get { return this._directoryName; }
private set { this._directoryName = this.CutPathDelimiter(value); }
}
public string UserName { get; private set; }
public string Password { get; private set; }
public int BufferSize { get; set; }
public bool UseBinary { get; set; }
public bool KeepAlive { get; set; }
public bool UsePassive { get; set; }
public FTPClient(string serverName, string dirName, string userName, string password, int bufferSize = 8192, bool useBinary = true, bool keepAlive = true, bool usePassive = false)
{
this.ServerName = serverName;
this.DirectoryName = dirName;
this.UserName = userName;
this.Password = password;
this.BufferSize = bufferSize;
this.UseBinary = useBinary;
this.KeepAlive = keepAlive;
this.UsePassive = usePassive;
}
private string CutPathDelimiter(string value)
{
var tail = value.Substring(0, 1, reverse: true);
if ((tail == @"\") || (tail == @"/")) return value.Substring(0, (value.Length - 1));
return value;
}
public void UploadFile(string targetFile, string destFileName, string destDirPath = null)
{
using (var fs = new System.IO.FileStream(targetFile, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, FileShare.None))
{
try
{
var ftpReq = this.GetFtpWebRequest(destFileName, destDirPath);
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
using (var reqStrm = ftpReq.GetRequestStream()) //★この時点で転送先にファイルが生成される★
{
byte[] buffer = new byte[this.BufferSize];
while (true)
{
int readSize = fs.Read(buffer, 0, buffer.Length);
if (readSize == 0) break;
reqStrm.Write(buffer, 0, readSize);
}
}
}
catch (Exception ex)
{
ex.WriteLog(string.Format("≪処理中ファイル情報≫\n送信元ファイル:[{0}]\n送信先ファイル:[{1}]\n送信先ディレクトリ:[{2}]", targetFile, destFileName, destDirPath));
throw;
}
}
}
private FtpWebRequest GetFtpWebRequest(string targetFileName, string destDirPath = null)
{
Uri targetUri;
var directory = destDirPath ?? this._directoryName;
if ((string.IsNullOrEmpty(destDirPath))) targetUri = new Uri(string.Format(@"{0}/{1}", this.ServerName, targetFileName));
else targetUri = new Uri(string.Format(@"{0}/{1}\{2}", this.ServerName, directory, targetFileName));
var ftpReq = (FtpWebRequest)WebRequest.Create(targetUri);
ftpReq.Credentials = new NetworkCredential(this.UserName, this.Password);
ftpReq.UseBinary = this.UseBinary;
ftpReq.KeepAlive = this.KeepAlive;
ftpReq.UsePassive = this.UsePassive;
return ftpReq;
}
private void DeleteFile(string targetFileName, string destDirPath = null)
{
try
{
var ftpReq = this.GetFtpWebRequest(targetFileName, destDirPath);
ftpReq.Method = WebRequestMethods.Ftp.DeleteFile;
using (FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse()) { }
}
catch (Exception ex)
{
ex.WriteLog(string.Format("≪処理中ファイル情報≫\n削除ファイル:[{0}]\nディレクトリ:[{1}]", targetFileName, destDirPath));
throw;
}
}
private bool IsExistsInDestDirFiles(string fileName)
{
try
{
// Uri targetUri = new Uri(string.Format("{0}{1}", ftpConf.FTPServerName, ftpConf.PutDirName));
// FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(targetUri);
// ftpReq.UseBinary = true;
// ftpReq.Credentials = new NetworkCredential(ftpConf.UserName, ftpConf.Password);
// ftpReq.Method = WebRequestMethods.Ftp.ListDirectory;
// ftpReq.KeepAlive = true;
// ftpReq.UsePassive = false;
// using (FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse())
// {
// using (System.IO.StreamReader sr = new System.IO.StreamReader(ftpRes.GetResponseStream()))
// {
// char[] splitChar = { Constants.vbLf };
// //区切り文字指定
// string stringRes = sr.ReadToEnd().Replace(Constants.vbCr, "");
// //Crが含まれる場合は消去
// List<string> listRes = stringRes.Split(splitChar).ToList;
// //区切り文字でリスト生成
// //ファイルが存在しない場合は空文字の配列が一つできるので、2つ以上でファイルが一つ以上存在する事になる。
// if ((listRes.Count > 1))
// {
// return listRes.GetRange(0, listRes.Count - 1).Contains(fileName);
// }
// else
// {
// return false;
// }
// }
// }
return true;
}
catch (WebException ex)
{
//送信先FTPサーバーOSによってLSコマンドの結果が異なる事による対応
//ファイルリスト取得先フォルダにファイルが一つも存在しない場合に、
//滴下サーバーでは、ファイルは無かったという正常応答、
//工程サーバーでは、550 No such file or directoryでエラー応答した。
//上記結果は、枚葉管理FTP送信端末からのFTPコマンドで確認、
//対応前プログラムの工程サーバー送信時の例外メッセージでも同様のメッセージを確認した。
//よって、この例外は正常(ファイル無し)として処理するように本プログラムで対応した。
FtpWebResponse res = (FtpWebResponse)ex.Response;
if ((res.StatusDescription.ToUpper().Replace(" ", "").Contains("NOSUCHFILEORDIRECTORY") && (res.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)))
{
//通常はファイルが無い場合、滴下サーバーはココを通るハズ!
//このパターンは日常的に発生するので、ログは採取しない。
return false;
}
else
{
//通常は無いハズだが、何かあった時のログ取りの為、この場合はメッセージを残す。
//this._log.Debug(ex, string.Format("{0}にて、転送先ファイル存在確認に失敗しました。{4}[Destination]{4}{1}{4}[Description]{4}{2}{4}[ErrorCode]{4}{3}", ftpConf.TransferName, string.Format("Server:[{0}] Dir:[{1}] FileName:[{2}]", ftpConf.FTPServerName, ftpConf.PutDirName, fileName), res.StatusDescription, res.StatusCode, Constants.vbCrLf));
return false;
//Throw ex
}
}
catch
{
//通常は無いハズだが、何かあった時のログ取りの為、この場合はメッセージを残す。
//this._log.Debug(ex, string.Format("{0}にて、転送先ファイル存在確認に失敗しました。{4}[Destination]{4}{1}{4}[Description]{4}{2}{4}[Source]{4}{3}", ftpConf.TransferName, string.Format("Server:[{0}] Dir:[{1}] FileName:[{2}]", ftpConf.FTPServerName, ftpConf.PutDirName, fileName), ex.Message, ex.Source, Constants.vbCrLf));
return false;
}
}
public void Disconnect()
{
try
{
Uri targetUri = new Uri(this.ServerName);
var ftpReq = (FtpWebRequest)WebRequest.Create(targetUri);
ftpReq.Credentials = new NetworkCredential(this.UserName, this.Password);
ftpReq.Method = WebRequestMethods.Ftp.PrintWorkingDirectory; //ダミーコマンド
ftpReq.KeepAlive = false;
using (FtpWebResponse ftpRes = (FtpWebResponse)ftpReq.GetResponse()) { }
}
catch (Exception ex)
{
ex.WriteLog();
}
}
}
}
|
6b143d4158aabcac6fd66ecbb9054ab86e686763
|
C#
|
kannan-ar/SharreShopping
|
/src/server/Models/ModelUtility.cs
| 2.640625
| 3
|
namespace server.Models
{
using System;
public class ModelUtility
{
public const string DateFormat = "dd/MM/yyyy";
public static DateTime GetDateTimeFromUnixTime(Int64 time)
{
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(time);
}
}
}
|
47e185d3614e3ecb94914a75666306a7d55d31e1
|
C#
|
DoughBoiKush/RS-Unity-1
|
/Assets/RS/util/TextureUtils.cs
| 3.484375
| 3
|
using System.Collections.Generic;
using UnityEngine;
namespace RS
{
/// <summary>
/// Provides utilities relating to unity textures.
/// </summary>
public static class TextureUtils
{
/// <summary>
/// Flips all pixels in the image horizontally.
/// </summary>
/// <param name="original">The texture to flip.</param>
/// <returns>The flipped texture.</returns>
public static Texture2D FlipHorizontal(Texture2D original)
{
Texture2D flipped = new Texture2D(original.width, original.height);
int width = original.width;
int height = original.height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
flipped.SetPixel(width - x - 1, y, original.GetPixel(x, y));
}
}
flipped.Apply();
return flipped;
}
/// <summary>
/// Flips all pixels in the image vertically.
/// </summary>
/// <param name="original">The texture to flip.</param>
/// <returns>The flipped texture.</returns>
public static Texture2D FlipVertical(Texture2D original)
{
Texture2D flipped = new Texture2D(original.width, original.height);
int width = original.width;
int height = original.height;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
flipped.SetPixel(x, height - y - 1, original.GetPixel(x, y));
}
}
flipped.Apply();
return flipped;
}
/// <summary>
/// Replaces a color in the provided texture.
/// </summary>
/// <param name="tex">The texture to replace the colors in.</param>
/// <param name="from">The color to replace.</param>
/// <param name="to">The color to replace the from color with.</param>
public static void Replace(Texture2D tex, Color from, Color to)
{
for (int x = 0; x < tex.width; x++)
{
for (int y = 0; y < tex.height; y++)
{
var col = tex.GetPixel(x, y);
if (col.r == from.r && col.g == from.g && col.b == from.b)
{
tex.SetPixel(x, y, to);
}
}
}
tex.Apply();
}
/// <summary>
/// Creates a 1x1 texture with the provided color.
/// </summary>
/// <param name="r">The red value.</param>
/// <param name="g">The green value.</param>
/// <param name="b">The blue value.</param>
/// <param name="a">The alpha value.</param>
/// <returns>The texture to create.</returns>
public static Texture2D CreateTextureOfColor(float r, float g, float b, float a)
{
Texture2D tex = new Texture2D(1, 1, TextureFormat.RGBA32, false);
tex.SetPixel(0, 0, new Color(r, g, b, a));
tex.Apply();
return tex;
}
/// <summary>
/// Creates a 1x1 texture with the provided color.
/// </summary>
/// <param name="r">The red value.</param>
/// <param name="g">The green value.</param>
/// <param name="b">The blue value.</param>
/// <param name="a">The alpha value.</param>
/// <returns>The texture to create.</returns>
public static Texture2D CreateTextureOfColor(byte r, byte g, byte b, byte a)
{
Texture2D tex = new Texture2D(1, 1, TextureFormat.RGBA32, false);
tex.SetPixel(0, 0, new Color32(r, g, b, a));
tex.Apply();
return tex;
}
/// <summary>
/// Creates a 1x1 texture with the provided color.
/// </summary>
/// <param name="r">The red value.</param>
/// <param name="g">The green value.</param>
/// <param name="b">The blue value.</param>
/// <param name="a">The alpha value.</param>
/// <returns>The texture to create.</returns>
public static Texture2D CreateTextureOfColor(int r, int g, int b, int a)
{
return CreateTextureOfColor((byte)r, (byte)g, (byte)b, (byte)a);
}
/// <summary>
/// Creates a 1x1 texture with the provided color.
/// </summary>
/// <param name="rgb">The RGB values.</param>
/// <param name="a">The alpha value.</param>
/// <returns>The texture to create.</returns>
public static Texture2D CreateTextureOfColor(int rgb, int a)
{
return CreateTextureOfColor((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF, a);
}
/// <summary>
/// Rotates a texture by the provided angle.
/// </summary>
/// <param name="tex">The texture to rotate.</param>
/// <param name="n">The angle to rotate by.</param>
/// <returns>The rotated texture.</returns>
public static Texture2D Rotate(Texture2D tex, int n)
{
Texture2D @new = new Texture2D(tex.width, tex.height, tex.format, false, true);
@new.SetPixels32(ColorUtils.RotateMatrix(tex.GetPixels32(), n));
@new.Apply();
return @new;
}
/// <summary>
/// Determines if the provided texture has any transparency.
/// </summary>
/// <param name="tex">The texture to check.</param>
/// <returns>If the provided texture has transparency.</returns>
public static bool HasTransparency(Texture2D tex)
{
var pixels = tex.GetPixels32();
foreach (var col in pixels)
{
if (col.a < 255)
{
return true;
}
}
return false;
}
/// <summary>
/// Draws a texture into the provided pixels.
/// </summary>
/// <param name="pixels">The pixels to draw into.</param>
/// <param name="pixelsWidth">The pixel width.</param>
/// <param name="pixelsHeight">The pixel height.</param>
/// <param name="tex">The texture to draw.</param>
/// <param name="x">The x coordinate to draw at.</param>
/// <param name="y">The y coordinate to draw at.</param>
public static void Draw(int[] pixels, int pixelsWidth, int pixelsHeight, Texture2D tex, int x, int y)
{
var from = tex.GetPixels32();
var ptr = (y * pixelsWidth) + x;
for (var cy = 0; cy < tex.height; cy++)
{
var off = ptr;
for (var cx = 0; cx < tex.width; cx++)
{
var col = from[cx + (cy * tex.width)];
var rgb = 0;
rgb |= (col.r) << 16;
rgb |= (col.g) << 8;
rgb |= (col.b);
if (rgb != 0)
{
pixels[off] = rgb;
}
off += 1;
}
ptr += pixelsWidth;
}
}
/// <summary>
/// Draws a texture into the provided pixels.
/// </summary>
/// <param name="pixels">The pixels to draw into.</param>
/// <param name="pixelsWidth">The pixel width.</param>
/// <param name="pixelsHeight">The pixel height.</param>
/// <param name="tex">The texture to draw.</param>
/// <param name="x">The x coordinate to draw at.</param>
/// <param name="y">The y coordinate to draw at.</param>
public static void Draw(Color[] pixels, int pixelsWidth, int pixelsHeight, Texture2D tex, int x, int y)
{
var from = tex.GetPixels32();
var ptr = (y * pixelsWidth) + x;
for (var cy = 0; cy < tex.height; cy++)
{
var off = ptr;
for (var cx = 0; cx < tex.width; cx++)
{
var col = from[cx + (cy * tex.width)];
var rgb = 0;
rgb |= (col.r) << 16;
rgb |= (col.g) << 8;
rgb |= (col.b);
if (rgb != 0)
{
pixels[off] = col;
}
off += 1;
}
ptr += pixelsWidth;
}
}
/// <summary>
/// Creates a palette of all of the colors in the provided texture.
/// </summary>
/// <param name="tex">The texture to generate a palette out of.</param>
/// <returns>All colors in the provided texture.</returns>
public static List<int> GetPalette(Texture2D tex)
{
var list = new List<int>();
var pixels = tex.GetPixels32();
for (var i = 0; i < pixels.Length; i++)
{
var pixel = pixels[i];
var rgb = (pixel.r << 16) | (pixel.g << 8) | (pixel.b);
if (!list.Contains(rgb))
{
list.Add(rgb);
}
}
return list;
}
/// <summary>
/// Calculates the average RGB value of the provided texture.
/// </summary>
/// <param name="tex">The texture to calculate the average RGB of.</param>
/// <returns>The average RGB value of the provided texture.</returns>
public static int GetAverageRGB(Texture2D tex)
{
int red = 0;
int green = 0;
int blue = 0;
var palette = GetPalette(tex);
var count = palette.Count;
for (int i = 0; i < count; i++)
{
var crgb = palette[i];
red += crgb >> 16 & 0xff;
green += crgb >> 8 & 0xff;
blue += crgb & 0xff;
}
int rgb = ColorUtils.LinearRGBBrightness(((red / count) << 16) + ((green / count) << 8) + (blue / count), 1.3999999999999999D);
if (rgb == 0)
{
rgb = 1;
}
return rgb;
}
/// <summary>
/// Creates a copy of the provided texture.
/// </summary>
/// <param name="tex">The texture to copy.</param>
/// <returns>The texture copy.</returns>
public static Texture2D Copy(Texture2D tex)
{
var copy = new Texture2D(tex.width, tex.height, tex.format, false);
copy.SetPixels(tex.GetPixels());
copy.Apply();
return copy;
}
}
}
|
3d675f3cb3c05ce33fe1774896a4528bdeebe5ba
|
C#
|
Seqiiu/SPOJ-1
|
/Spoj.Solver/Solutions/4 - Prince/WILLITST.cs
| 3.859375
| 4
|
using System;
// https://www.spoj.com/problems/WILLITST/ #game #math
// Determines if the specified algorithm ever stops for a given input.
public static class WILLITST
{
// If the second branch gets hit, the number maps to 3(n + 1) and definitely
// has a factor of 3. That means that second branch eventually gets hit again,
// even if a lot of factors of 2 get divided out. And when it's hit again, it
// still has a factor of 3 after mapping to 3(n + 1), and the process repeats...
// So, only powers of two will ever stop.
public static bool Solve(long n)
=> n <= 1 || IsPowerOfTwo(n);
// http://stackoverflow.com/a/600306
private static bool IsPowerOfTwo(long n)
=> n <= 0 ? false : (n & (n - 1)) == 0;
}
public static class Program
{
private static void Main()
{
Console.WriteLine(
WILLITST.Solve(long.Parse(Console.ReadLine())) ? "TAK" : "NIE");
}
}
|
5b8a291504c22cc4f89c3ea404341919881c2270
|
C#
|
goranalkovic/FOIapp-UWP
|
/FOIapp/Classes/CourseItem.cs
| 2.65625
| 3
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using FOIapp.Annotations;
namespace FOIapp.Classes
{
public class CourseItem : INotifyPropertyChanged
{
private double currentPoints;
public int CourseItemID { get; set; }
public int CourseID { get; set; }
public int CategoryID { get; set; }
public string Name { get; set; }
public double Points { get; set; }
public double MinPoints { get; set; }
public double CurrentPoints
{
get { return currentPoints; }
set
{
currentPoints = value;
OnPropertyChanged(nameof(CurrentPoints));
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
09ae71edbf6ca07ac34dd7ee27bcd89b2f756396
|
C#
|
lehuyhieu10999/C0220I1
|
/Module2/CoffeeManagement/CoffeeManagement/Services/CofffeeService.cs
| 3.015625
| 3
|
using CoffeeManagement.Models;
using System;
using System.Collections.Generic;
namespace CoffeeManagement.Services
{
class CofffeeService
{
public Data data;
private string path;
private string databasename;
private string fullpath => @$"{path}\{databasename}";
public CofffeeService(string _path, string _databasename)
{
data = new Data()
{
tables = new List<Table>()
};
path = _path;
databasename = _databasename;
ReadWriteService<Data>.ReadData(fullpath, data);
}
public string ShowAll()
{
string str = "";
foreach (var table in data.tables)
{
str = $"{str}\n{table.ToString()}";
}
return str;
}
public bool NewOrder(Table table)
{
try
{
data.tables.Add(table);
ReadWriteService<Data>.WriteData(fullpath, data);
return true;
}
catch(Exception e)
{
return false;
}
}
public bool UpdateOrder(string tableId, List<OrderDetail> orderDetails)
{
try
{
var table = Check(tableId);
if(table != null)
{
foreach(var od in orderDetails)
{
table.orderdetails.Add(od);
}
ReadWriteService<Data>.WriteData(fullpath, data);
return true;
}
return false;
}
catch(Exception e)
{
return false;
}
}
public string ShowTable(string tableId)
{
var table = Check(tableId);
if (table != null)
return table.ToString();
return string.Empty;
}
public bool Pay(string tableId)
{
try
{
var table = Check(tableId);
if(table != null)
{
table.endtime = DateTime.Now.ToString("dd/MM/yyyy hh:mm tt");
table.ispaid = true;
ReadWriteService<Data>.WriteData(fullpath, data);
PrintBill(table);
return true;
}
return false;
}
catch(Exception e)
{
return false;
}
}
public bool PrintBill(Table table)
{
try
{
string billName = $"bill_{table.tableid}_{DateTime.Now.ToString("ddMMyyyyhhmmtt")}.json";
string fullBill = @$"{path}\{billName}";
ReadWriteService<Table>.WriteData(fullBill, table);
return true;
}
catch(Exception e)
{
return false;
}
}
public Table Check(string tableId)
{
foreach(var table in data.tables)
{
if (table.tableid.Equals(tableId) && !table.ispaid)
{
return table;
}
}
return null;
}
}
}
|
db7cf58befa3360232a83e58ac3042db80bbf4cd
|
C#
|
BasicLich/Hooks
|
/Assets/Scripts/State Machine/State.cs
| 2.703125
| 3
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class State : MonoBehaviour
{
protected List<StateComponent> updateComponents = new List<StateComponent>();
protected List<StateComponent> fixedUpdateComponents = new List<StateComponent>();
protected List<StateComponent> noExecuteComponents = new List<StateComponent>();
public State PreviousState { get; set; }
public void Awake()
{
StateComponent[] components = GetComponents<StateComponent>();
foreach(StateComponent component in components)
{
this.Register(component);
}
}
public void Register(StateComponent component)
{
if (component == null) return;
switch (component.GetStateComponentType())
{
case StateComponentType.FIXED_UPDATE:
this.fixedUpdateComponents.Add(component);
break;
case StateComponentType.UPDATE:
this.updateComponents.Add(component);
break;
default:
this.noExecuteComponents.Add(component);
break;
}
}
public State Execute()
{
foreach (StateComponent component in this.updateComponents)
{
State newState = component.Execute();
if (newState != null)
{
return newState;
}
}
return null;
}
public State FixedExecute()
{
foreach (StateComponent component in this.fixedUpdateComponents)
{
State newState = component.Execute();
if (newState != null)
{
return newState;
}
}
return null;
}
public virtual void Enter()
{
foreach(StateComponent component in this.updateComponents)
{
component.Enter();
}
foreach (StateComponent component in this.fixedUpdateComponents)
{
component.Enter();
}
foreach (StateComponent component in this.noExecuteComponents)
{
component.Enter();
}
}
public virtual void Exit()
{
foreach (StateComponent component in this.updateComponents)
{
component.Exit();
}
foreach (StateComponent component in this.fixedUpdateComponents)
{
component.Exit();
}
foreach (StateComponent component in this.noExecuteComponents)
{
component.Exit();
}
}
}
|
6a49f56341a91c72cee3dc7188f542ad0d8a3f2d
|
C#
|
makarevichmatvei/proekt-testPO
|
/Calc142/Calc142/TwoArgument/Percent.cs
| 2.59375
| 3
|
using System;
namespace Calc142
{
public class Percent: ITwoArgCalc
{
public double Calculate(double firstArg, double secondArg)
{
return (firstArg * secondArg) / 100;
}
}
}
|
0681fd86b11c9cb5306c73881dae429a6bb9caf0
|
C#
|
watfordgnf/Jwt
|
/test/JsonWebToken.Tests/JsonObjectTests.cs
| 2.6875
| 3
|
using JsonWebToken.Cryptography;
using Xunit;
namespace JsonWebToken.Tests
{
public class JsonObjectTests
{
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(4)]
[InlineData(5)]
[InlineData(6)]
[Theory]
public void AddReplacesExistingMember(int initialMemberCount)
{
JsonObject o = new JsonObject();
for( int i = 0; i<initialMemberCount;++i)
{
o.Add(i.ToString(), "Padding");
}
o.Add("A", true);
Assert.True(o.TryGetValue("A", out var vT));
Assert.True((bool)vT.Value);
Assert.Equal(initialMemberCount + 1, o.Count);
o.Add("A", false);
Assert.True(o.TryGetValue("A", out var vF) && vF.Value.Equals(false));
Assert.Equal(initialMemberCount + 1, o.Count);
}
}
}
|
0d469596b96595e6bb9a73faf9ddb92f59e768bf
|
C#
|
vladar21/Clinic
|
/Clinic/Appointment.cs
| 2.703125
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace Clinic
{
public partial class Appointment : Form
{
int patientid { set; get; }
int docid { set; get; }
public Appointment(int id, Dictionary<Int32, String> listDocs)
{
InitializeComponent();
this.StartPosition = FormStartPosition.Manual;
patientid = id;
textBoxYourID.Enabled = false;
textBoxYourID.Text = id.ToString();
comboBoxChooseDoc.DataSource = new BindingSource(listDocs, null);
comboBoxChooseDoc.DisplayMember = "Value";
comboBoxChooseDoc.ValueMember = "Key";
comboBoxChooseDoc.SelectedIndex = -1;
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.MinDate = DateTime.Today;
dateTimePicker1.MaxDate = dateTimePicker1.Value.AddMonths(1);
}
private void Appointment_FormClosed(object sender, FormClosedEventArgs e)
{
// вызываем главную форму, которая открыла текущую, главная форма всегда = 0 - [0]
Form ifrm = Application.OpenForms[0];
ifrm.StartPosition = FormStartPosition.Manual; // меняем параметр StartPosition у Form1, иначе она будет использовать тот, который у неё прописан в настройках и всегда будет открываться по центру экрана
ifrm.Left = this.Left; // задаём открываемой форме позицию слева равную позиции текущей формы
ifrm.Top = this.Top; // задаём открываемой форме позицию сверху равную позиции текущей формы
ifrm.Show(); // отображаем Form1
}
private void btnAppointmentOk_Click(object sender, EventArgs e)
{
if (dateTimePicker1.Value != null && comboBoxChooseDoc.Text.Length > 0)
{
using (clinicEntities db = new clinicEntities())
{
dateTimePicker1.CustomFormat = "yyyy-mm-dd";
DateTime Date = dateTimePicker1.Value.Date;
var existdoc = db.appointments.Where(x => x.doc_id == docid && x.patient_id == patientid && x.appday == Date).FirstOrDefault();
if (existdoc == null)
{
appointments appo = new appointments();
appo.appday = dateTimePicker1.Value;
appo.doc_id = docid;
appo.patient_id = patientid;
db.appointments.Add(appo);
db.SaveChanges();
Form schfrm = new Schedule(patientid, "Patient");
schfrm.Left = this.Left; // задаём открываемой форме позицию слева равную позиции текущей формы
schfrm.Top = this.Top; // задаём открываемой форме позицию сверху равную позиции текущей формы
schfrm.Show(); // отображаем Form2
this.Hide(); // скрываем Form1 (this - текущая форма)
}
else { MessageBox.Show("You already made this entry."); }
}
}
}
private void comboBoxChooseDoc_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxChooseDoc.SelectedIndex == -1) docid = 0;
else docid = ((KeyValuePair<int, string>)comboBoxChooseDoc.SelectedItem).Key;
}
}
}
|
52224f824f53ed191dbc48a0e5f8cddfa23d062f
|
C#
|
Julia-Alexandrova/teamcity-runas-plugin
|
/runAs-tool-win32/JetBrains.runAs.IntegrationTests/RunSteps.cs
| 2.59375
| 3
|
namespace JetBrains.runAs.IntegrationTests
{
using System;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.runAs.IntegrationTests.Dsl;
using NUnit.Framework;
using TechTalk.SpecFlow;
using System.Collections.Generic;
using TestContext = JetBrains.runAs.IntegrationTests.Dsl.TestContext;
[Binding]
public class RunSteps
{
[Given(@"I've added the argument (.+)")]
public void AddArg(string arg)
{
if (string.IsNullOrEmpty(arg))
{
return;
}
var ctx = ScenarioContext.Current.GetTestContext();
ctx.CommandLineSetup.Arguments.Add(arg);
}
[Given(@"I've added the argument\s+")]
public void AddEmptyArg()
{
}
[Given(@"I've defined the (.+) environment variable by the value (.+)")]
public void AddEnvVar(string name, string value)
{
var ctx = ScenarioContext.Current.GetTestContext();
ctx.CommandLineSetup.EnvVariables[name] = value;
}
[When(@"I run RunAs tool")]
public void RunRunAsTool()
{
var ctx = ScenarioContext.Current.GetTestContext();
var runner = new RunAsRunner();
var testSession = runner.Run(ctx);
ctx.TestSession = testSession;
}
[Then(@"the exit code should be (.+)")]
public void VerifyExitCode(string expectedExitCodeRegexp)
{
var ctx = ScenarioContext.Current.GetTestContext();
var regex = new Regex(expectedExitCodeRegexp);
Assert.IsTrue(regex.Match(ctx.TestSession.ExitCode.ToString()).Success, $"Invalid exit code.\nSee {ctx}");
}
[Then(@"the output should contain:")]
public void CheckOutput(Table table)
{
var ctx = ScenarioContext.Current.GetTestContext();
var testSession = ctx.TestSession;
CheckText(ctx, testSession.Output, table);
}
[Then(@"the errors should contain:")]
public void CheckErrors(Table table)
{
var ctx = ScenarioContext.Current.GetTestContext();
var testSession = ctx.TestSession;
CheckText(ctx, testSession.Errors, table);
}
private static void CheckText(TestContext ctx, string text, Table table)
{
var separator = new[] { Environment.NewLine };
var lines = new List<string>(text.Split(separator, StringSplitOptions.None));
var parrents = new List<Regex>(table.Rows.Select(i => new Regex(i[""], RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled)));
while (lines.Count > 0 && parrents.Count > 0)
{
var line = lines[0];
lines.RemoveAt(0);
if (parrents[0].IsMatch(line))
{
parrents.RemoveAt(0);
}
}
if (parrents.Any())
{
Assert.Fail($"Patterns are not matched:\n{string.Join(Environment.NewLine, parrents)}\nOutput:\n{text}\n\nSee {ctx}");
}
}
}
}
|
405d22378d426f21673c2d3b4c8d9365653c52e5
|
C#
|
ZhouHengYi/HFramework
|
/H.Front/H.Facade/LanguageHelper.cs
| 2.515625
| 3
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using H.Core.Utility;
namespace H.Facade
{
public class LanguageHelper
{
private static string GetLanguageType() {
string language = CookieManager.GetValue("WebsiteLanguage");
return language;
}
public static string GetMessage(string code) {
string fileUrl = string.Empty;
switch (GetLanguageType())
{
case "en":
fileUrl = "Configuration/Language/EN/language_cn.config";
break;
case "jp":
fileUrl = "Configuration/Language/JP/language_cn.config";
break;
default:
fileUrl = "Configuration/Language/CN/language_cn.config";
break;
}
fileUrl = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, fileUrl);
XmlDocument doc = new XmlDocument();
doc.Load(fileUrl);
XmlNodeList nodes = doc.SelectNodes("/messageConfig/message[@code='"+code+"']");
string message = string.Empty;
foreach (XmlNode item in nodes)
{
message = item.InnerText;
}
return message;
}
public static string GetLanguageScriptPath() {
string fileUrl = string.Empty;
switch (GetLanguageType())
{
case "en":
fileUrl = "/Configuration/Language/EN/language_cn.js";
break;
case "jp":
fileUrl = "/Configuration/Language/JP/language_cn.js";
break;
default:
fileUrl = "/Configuration/Language/CN/language_cn.js";
break;
}
return fileUrl;
}
}
}
|
0521194fc16e1b97713244e92a60a40306cc88d6
|
C#
|
hez2010/SATSP
|
/NotConverter.cs
| 2.703125
| 3
|
using Avalonia.Data.Converters;
using System;
using System.Globalization;
namespace SATSP
{
public sealed class NotConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool b) return !b;
if (value is null) return true;
throw new InvalidCastException("Source type is not boolean.");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool b) return !b;
throw new InvalidCastException("Source type is not boolean.");
}
}
}
|
148eb1ea61b13a0cdb9746f3b4fc0f2d72269dc1
|
C#
|
Despairon/Physics_Simulation
|
/Physics_Simulation/ObjFileReader.cs
| 2.734375
| 3
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Physics_Simulation
{
public static class ObjFileReader
{
#region private_members
private enum Global_State
{
IDLE,
IN_PROCESS
}
private enum Local_State
{
IDLE = 0,
READING_COMMENT,
READING_VERTEX,
READING_TEXCOORD,
READING_NORMAL,
READING_MESH,
READING_FACE,
READING_SMOOTHING,
READING_MTLLIB,
READING_USEMTL
}
private struct FSM_Table_item
{
public FSM_Table_item(Local_State nextState, string cmd, func cmd_func)
{
this.nextState = nextState;
this.cmd = cmd;
this.cmd_func = cmd_func;
}
public Local_State nextState;
public string cmd;
public func cmd_func;
public delegate void func(ObjFile objFile);
}
private static List<FSM_Table_item> fsm_table = new List<FSM_Table_item>()
{
new FSM_Table_item(Local_State.READING_COMMENT, "#", FSM_Callbacks.read_commend),
new FSM_Table_item(Local_State.READING_VERTEX, "v", FSM_Callbacks.read_vertex),
new FSM_Table_item(Local_State.READING_TEXCOORD, "vt", FSM_Callbacks.read_texcoord),
new FSM_Table_item(Local_State.READING_NORMAL, "vn", FSM_Callbacks.read_normal),
new FSM_Table_item(Local_State.READING_MESH, "g", FSM_Callbacks.read_mesh),
new FSM_Table_item(Local_State.READING_MESH, "o", FSM_Callbacks.read_mesh),
new FSM_Table_item(Local_State.READING_FACE, "f", FSM_Callbacks.read_face),
new FSM_Table_item(Local_State.READING_SMOOTHING, "s", FSM_Callbacks.read_smoothing),
new FSM_Table_item(Local_State.READING_MTLLIB, "mtllib", FSM_Callbacks.read_mtllib),
new FSM_Table_item(Local_State.READING_USEMTL, "usemtl", FSM_Callbacks.read_usemtl)
};
private static Global_State _gState = Global_State.IDLE;
private static Local_State _lState = Local_State.IDLE;
private static void changeGlobalState(Global_State gState)
{
_gState = gState;
}
private static void changeLocalState(Local_State lState)
{
_lState = lState;
}
private static void execute_fsm(ObjFile objFile)
{
string cmd = objFile.nextCmd();
var fsm_table_item = fsm_table.Find(item => item.cmd == cmd);
if (fsm_table_item.cmd_func != null)
{
changeLocalState(fsm_table_item.nextState);
fsm_table_item.cmd_func(objFile);
}
}
private struct FSM_Callbacks
{
public static void read_commend(ObjFile objFile)
{
objFile.skipLine();
}
public static void read_vertex(ObjFile objFile)
{
var vertex_str = new List<string>(objFile.getLine().Split(' '));
vertex_str.RemoveAll(str => (str == "") || (str == " "));
if ((vertex_str.Count == 3) || (vertex_str.Count == 4 && vertex_str[3] != ""))
{
Vector3 vertex = new Vector3();
vertex.x = double.Parse(vertex_str[0], CultureInfo.InvariantCulture);
vertex.y = double.Parse(vertex_str[1], CultureInfo.InvariantCulture);
vertex.z = double.Parse(vertex_str[2], CultureInfo.InvariantCulture);
objFile.vertices.Add(vertex);
}
}
public static void read_texcoord(ObjFile objFile)
{
var texcoord_str = new List<string>(objFile.getLine().Split(' '));
texcoord_str.RemoveAll(str => (str == "") || (str == " "));
if (texcoord_str.Count == 2 || (texcoord_str.Count == 3 && texcoord_str[2] != ""))
{
Vector2 texcoord = new Vector2();
texcoord.x = double.Parse(texcoord_str[0], CultureInfo.InvariantCulture);
texcoord.y = double.Parse(texcoord_str[1], CultureInfo.InvariantCulture);
objFile.texcoords.Add(texcoord);
}
}
public static void read_normal(ObjFile objFile)
{
var normal_str = new List<string>(objFile.getLine().Split(' '));
normal_str.RemoveAll(str => (str == "") || (str == " "));
if (normal_str.Count == 3 || (normal_str.Count == 4 && normal_str[3] != ""))
{
Vector3 normal = new Vector3();
normal.x = double.Parse(normal_str[0], CultureInfo.InvariantCulture);
normal.y = double.Parse(normal_str[1], CultureInfo.InvariantCulture);
normal.z = double.Parse(normal_str[2], CultureInfo.InvariantCulture);
objFile.normals.Add(normal);
}
}
public static void read_mesh(ObjFile objFile)
{
var group_str = objFile.getLine();
if (group_str != "")
{
var mesh = new ObjFile.Mesh(group_str);
objFile.addMesh(mesh);
}
}
public static void read_face(ObjFile objFile)
{
var face_str = objFile.getLine();
var mesh = objFile.currMesh;
var face_str_splitted = new List<string>(face_str.Split(' '));
face_str_splitted.RemoveAll(str => (str == "") || (str == " "));
List<int> vertex_indices = new List<int>();
List<int> texcoord_indices = new List<int>();
List<int> normal_indices = new List<int>();
foreach (var str in face_str_splitted)
{
var str_splitted = str.Split('/');
int vertex_index = 0;
int texcoord_index = 0;
int normal_index = 0;
switch (str_splitted.Length)
{
case 1:
{
vertex_index = Convert.ToInt32(str_splitted[0]);
if (vertex_index < 0)
vertex_index = (objFile.vertices.Count - (vertex_index * -1) + 1);
}
break;
case 2:
{
vertex_index = Convert.ToInt32(str_splitted[0]);
if (vertex_index < 0)
vertex_index = (objFile.vertices.Count - (vertex_index * -1) + 1);
texcoord_index = Convert.ToInt32(str_splitted[1]);
if (texcoord_index < 0)
texcoord_index = (objFile.texcoords.Count - (texcoord_index * -1) + 1);
}
break;
case 3:
{
vertex_index = Convert.ToInt32(str_splitted[0]);
if (vertex_index < 0)
vertex_index = (objFile.vertices.Count - (vertex_index * -1) + 1);
if (str_splitted[1] != "")
{
texcoord_index = Convert.ToInt32(str_splitted[1]);
if (texcoord_index < 0)
texcoord_index = (objFile.texcoords.Count - (texcoord_index * -1) + 1);
}
normal_index = Convert.ToInt32(str_splitted[2]);
if (normal_index < 0)
normal_index = (objFile.normals.Count - (normal_index * -1) + 1);
}
break;
default: break;
}
if (vertex_index != 0)
vertex_indices.Add(vertex_index);
if (texcoord_index != 0)
texcoord_indices.Add(texcoord_index);
if (normal_index != 0)
normal_indices.Add(normal_index);
}
var face = new ObjFile.Mesh.Face(vertex_indices.ToArray(), texcoord_indices.ToArray(), normal_indices.ToArray());
mesh.faces.Add(face);
}
public static void read_smoothing(ObjFile objFile)
{
var smoothing_str = objFile.getLine();
// TODO: implement
}
public static void read_mtllib(ObjFile objFile)
{
var matlib_str = objFile.getLine();
objFile.setMatLib(matlib_str);
}
public static void read_usemtl(ObjFile objFile)
{
var usemtl_str = objFile.getLine();
// TODO: implement
}
}
#endregion
#region public_members
public static ObjFile read(string filename)
{
ObjFile objFile = null;
if (_gState == Global_State.IDLE)
{
changeGlobalState(Global_State.IN_PROCESS);
FileStream fs = new FileStream(filename, FileMode.Open);
if (fs != null)
{
if (fs.CanRead)
{
StreamReader sr = new StreamReader(fs);
if (sr != null)
{
string source = sr.ReadToEnd();
objFile = new ObjFile(filename, source);
while (!objFile.eof)
execute_fsm(objFile);
sr.Close();
}
}
fs.Close();
}
changeGlobalState(Global_State.IDLE);
}
return objFile;
}
public class ObjFile
{
#region private_members
private int index;
#endregion
#region public_members
public ObjFile(string name, string source)
{
this.name = name;
this.source = source;
vertices = new List<Vector3>();
texcoords = new List<Vector2>();
normals = new List<Vector3>();
meshes = new List<Mesh>();
index = 0;
}
public string name { get; private set; }
public string source { get; private set; }
public bool eof
{
get { return index == source.Length; }
}
public string nextCmd()
{
string cmd = "";
while (true)
{
cmd += source[index];
index++;
if (index == source.Length) break;
if (source[index] == '\n') break;
if (source[index] == '\0') break;
if (source[index] == ' ') break;
}
return cmd.Trim();
}
public void skipLine()
{
while ((source[index] != '\n') && (source[index] != '\0'))
index++;
}
public string getLine()
{
string line = "";
while ((source[index] != '\n') && (source[index] != '\0'))
{
line += source[index];
index++;
}
var trimmedLine = line.TrimStart().TrimEnd();
return trimmedLine;
}
public List<Vector3> vertices { get; private set; }
public List<Vector2> texcoords { get; private set; }
public List<Vector3> normals { get; private set; }
public string matlib { get; private set; }
private bool matlibSet = false;
public void setMatLib(string matlib)
{
if (!matlibSet)
{
this.matlib = matlib;
matlibSet = true;
}
}
public class Mesh
{
private string name;
public Mesh(string name)
{
this.name = name;
faces = new List<Face>();
}
public struct Face
{
public Face(int[] vertex_indices, int[] texcoord_indices, int[] normal_indices)
{
this.vertex_indices = vertex_indices;
this.texcoord_indices = texcoord_indices;
this.normal_indices = normal_indices;
}
public int[] vertex_indices;
public int[] texcoord_indices;
public int[] normal_indices;
}
public List<Face> faces { get; private set; }
}
public List<Mesh> meshes { get; private set; }
public Mesh currMesh { get; private set; }
public void addMesh(Mesh mesh)
{
meshes.Add(mesh);
currMesh = mesh;
}
}
#endregion
#endregion
}
}
|
fd968e771f51725c6c157b4fa1a0c7d723a8617d
|
C#
|
6624465/PickC01122018
|
/Operation.BusinessFactory/InvoiceBO.cs
| 2.609375
| 3
|
using System;
using System.Collections.Generic;
using Operation.Contract;
using Operation.DataFactory;
namespace Operation.BusinessFactory
{
public class InvoiceBO
{
private InvoiceDAL invoiceDAL;
public InvoiceBO()
{
invoiceDAL = new InvoiceDAL();
}
public List<Invoice> GetList()
{
return invoiceDAL.GetList();
}
public bool SaveInvoice(Invoice newItem)
{
return invoiceDAL.Save(newItem);
}
public bool DeleteInvoice(Invoice item)
{
return invoiceDAL.Delete(item);
}
public Invoice GetInvoice(Invoice item)
{
return (Invoice)invoiceDAL.GetItem<Invoice>(item);
}
public Invoice GetInvoiceByBookingNo(string bookingNo)
{
return (Invoice)invoiceDAL.GetInvoiceByBookingNo(bookingNo);
}
}
}
|
0d5bd03daba0af6c49dfd5a9ac0c0a97f43e269c
|
C#
|
google/or-tools
|
/ortools/sat/samples/CpSatExample.cs
| 2.625
| 3
|
// Copyright 2010-2022 Google LLC
// 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.
// [START program]
// [START import]
using System;
using System.Linq;
using Google.OrTools.Sat;
// [END import]
public class CpSatExample
{
static void Main()
{
// Creates the model.
// [START model]
CpModel model = new CpModel();
// [END model]
// Creates the variables.
// [START variables]
int varUpperBound = new int[] { 50, 45, 37 }.Max();
IntVar x = model.NewIntVar(0, varUpperBound, "x");
IntVar y = model.NewIntVar(0, varUpperBound, "y");
IntVar z = model.NewIntVar(0, varUpperBound, "z");
// [END variables]
// Creates the constraints.
// [START constraints]
model.Add(2 * x + 7 * y + 3 * z <= 50);
model.Add(3 * x - 5 * y + 7 * z <= 45);
model.Add(5 * x + 2 * y - 6 * z <= 37);
// [END constraints]
// [START objective]
model.Maximize(2 * x + 2 * y + 3 * z);
// [END objective]
// Creates a solver and solves the model.
// [START solve]
CpSolver solver = new CpSolver();
CpSolverStatus status = solver.Solve(model);
// [END solve]
// [START print_solution]
if (status == CpSolverStatus.Optimal || status == CpSolverStatus.Feasible)
{
Console.WriteLine($"Maximum of objective function: {solver.ObjectiveValue}");
Console.WriteLine("x = " + solver.Value(x));
Console.WriteLine("y = " + solver.Value(y));
Console.WriteLine("z = " + solver.Value(z));
}
else
{
Console.WriteLine("No solution found.");
}
// [END print_solution]
// [START statistics]
Console.WriteLine("Statistics");
Console.WriteLine($" conflicts: {solver.NumConflicts()}");
Console.WriteLine($" branches : {solver.NumBranches()}");
Console.WriteLine($" wall time: {solver.WallTime()}s");
// [END statistics]
}
}
// [END program]
|
43024661e553db854b9c224f5400b7065a42b8cd
|
C#
|
bbonkr/sample-multilingual-content
|
/src/Sample.MultilingualContent/Infrastructure/SomethingWrongException.cs
| 2.96875
| 3
|
using System;
namespace Sample.MultilingualContent
{
public abstract class SomethingWrongException : Exception
{
public SomethingWrongException(string message) : base(message) { }
public abstract object GetDetails();
}
public class SomethingWrongException<T> : SomethingWrongException where T : class
{
public SomethingWrongException(string message, T details) : base(message)
{
this.Details = details;
}
public T Details { get; init; }
public override T GetDetails()
{
return Details;
}
}
}
|
027e2588b49f0251116134b387f8cd383f4102e3
|
C#
|
MiguelAlvCar/GameAvocadosWars
|
/Sound/Effects.cs
| 2.8125
| 3
|
using System;
using System.Collections.Generic;
using System.Windows.Media;
using System.IO;
using WpfBasicElements.AbstractClasses;
namespace Sound
{
public class Effects: IEffects
{
public MediaPlayer AttackEffectsMediaPlayer { get; set; } = new MediaPlayer();
public MediaPlayer DefenseEffectsMediaPlayer { get; set; } = new MediaPlayer();
public double VolumenEffekte { get; set; }
public void Play(Uri uri, MediaPlayer mediaPlayerEffekte)
{
if (mediaPlayerEffekte != null) mediaPlayerEffekte.Close();
mediaPlayerEffekte.Open(uri);
mediaPlayerEffekte.Play();
mediaPlayerEffekte.Volume = VolumenEffekte;
}
}
public class UriEffect
{
private List<Uri> UriList = new List<Uri>();
public Uri EffectUri
{
get
{
Random EffectRandom = new Random();
int RandomEffectNumber = EffectRandom.Next(0, UriList.Count);
return UriList[RandomEffectNumber];
}
}
public UriEffect(string first5LettersOfSoundFiles, string directoryPath)
{
string[] pathsEffekte = Directory.GetFileSystemEntries(Environment.CurrentDirectory + directoryPath);
foreach (string path in pathsEffekte)
{
FileInfo file = new FileInfo(path);
if (file.Extension == ".wav" || file.Extension == ".m4v" || file.Extension == ".mp3" || file.Extension == ".mp4" || file.Extension == ".mp4v" || file.Extension == ".asx"
|| file.Extension == ".wax" || file.Extension == ".wvx" || file.Extension == ".wmx" || file.Extension == ".wpl" || file.Extension == "asf" || file.Extension == ".wma"
|| file.Extension == ".wmv" || file.Extension == ".wm" || file.Extension == ".mpg" || file.Extension == ".mpeg" || file.Extension == ".m1v" || file.Extension == ".mp2"
|| file.Extension == ".mpa" || file.Extension == ".mpe" || file.Extension == ".m3u" || file.Extension == ".mid" || file.Extension == ".midi" || file.Extension == ".rmi"
|| file.Extension == ".aif" || file.Extension == ".aifc" || file.Extension == ".aiff" || file.Extension == ".cda" || file.Extension == ".m4a" || file.Extension == ".3g2"
|| file.Extension == ".3gp2" || file.Extension == ".3gp" || file.Extension == ".3gpp" || file.Extension == ".aac" || file.Extension == ".adt" || file.Extension == ".adts")
{
if (file.Name.Substring(0, 5) == first5LettersOfSoundFiles)
{
UriList.Add(new Uri(path));
}
}
}
}
}
}
|
7e29ba6ccf9fcae8bbb9141667b86b3dd1de167c
|
C#
|
WakeDown/UnitApis
|
/Code/ApiDataProvider/Models/Stuff/WorkDay.cs
| 2.796875
| 3
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using DataProvider.Helpers;
namespace DataProvider.Models.Stuff
{
public class WorkDay
{
public static HolidayResult CheckIsPreHoliday(DateTime date)
{
var result = new HolidayResult() { SendDelivery = false };
SqlParameter pDate = new SqlParameter() { ParameterName = "date", SqlValue = date, SqlDbType = SqlDbType.Date };
var dt = Db.Stuff.ExecuteQueryStoredProcedure("check_is_work_day", pDate);
if (dt.Rows.Count > 0)
{
bool isWorkDay = Db.DbHelper.GetValueBool(dt.Rows[0], "result");
if (isWorkDay)
{
SqlParameter pDate1 = new SqlParameter()
{
ParameterName = "date",
SqlValue = date,
SqlDbType = SqlDbType.Date
};
var dt1 = Db.Stuff.ExecuteQueryStoredProcedure("get_next_work_day", pDate1);
if (dt1.Rows.Count > 0)
{
DateTime? nextWorkDate = Db.DbHelper.GetValueDateTimeOrNull(dt1.Rows[0], "date");
if (nextWorkDate.HasValue && nextWorkDate.Value.Date != date.AddDays(1).Date)
{
result.SendDelivery = true;
result.DateStart = date.AddDays(1).Date;
result.DateEnd = nextWorkDate.Value.Date.AddDays(-1);
result.IsSundayOnly = (result.DateStart.AddDays(1).Date == result.DateEnd.Date) &&
result.DateEnd.DayOfWeek == DayOfWeek.Sunday;
}
}
}
}
return result;
}
}
}
|
c0c271eb55d3392f1a239c826618b29fba3b6484
|
C#
|
christianspecht/bitbucket-backup
|
/src/BitbucketBackup/GitRepository.cs
| 2.765625
| 3
|
using System;
using System.IO;
namespace BitbucketBackup
{
/// <summary>
/// Creates and pulls from Git repositories.
/// </summary>
internal class GitRepository : RepositoryBase
{
private GitWrapper git;
public GitRepository(string remoteUri, string folder) : base(remoteUri, folder) { }
protected override void Init()
{
this.git = new GitWrapper(folder);
if (!File.Exists(Path.Combine(this.folder, "HEAD")))
{
this.git.Execute("init --bare");
}
}
public override string PullingMessage
{
get { return Resources.PullingGit; }
}
public override void Pull()
{
string output = this.git.Execute(String.Format("fetch --force --prune {0} refs/heads/*:refs/heads/* refs/tags/*:refs/tags/*", this.remoteuri));
if (output.Contains("Unauthorized") || output.Contains("Authentication failed"))
{
throw new ClientException(Resources.MissingPermissions, null);
}
}
}
}
|
7adfa72bc6f799ad2cbcb648efdeb1183209a497
|
C#
|
route4me/route4me-csharp-sdk
|
/route4me-csharp-sdk/Route4MeSDKTest/Examples/AddressBookGroup/GetAddressBookGroups.cs
| 2.578125
| 3
|
using Route4MeSDK.DataTypes;
using Route4MeSDK.QueryTypes;
using System;
namespace Route4MeSDK.Examples
{
public sealed partial class Route4MeExamples
{
/// <summary>
/// Get the address book groups
/// </summary>
public void GetAddressBookGroups()
{
var route4Me = new Route4MeManager(ActualApiKey);
var addressBookGroupParameters = new AddressBookGroupParameters()
{
Limit = 10,
Offset = 0
};
// Run the query
AddressBookGroup[] groups = route4Me
.GetAddressBookGroups(addressBookGroupParameters, out string errorString);
Console.WriteLine(
groups == null && groups.GetType() != typeof(AddressBookGroup[])
? "Cannot retrieve the addres groups." + Environment.NewLine + errorString
: "Retrieved the address book groups: " + groups.Length
);
RemoveAddressBookGroups();
}
}
}
|
d58c65938fd19c5ee032e99fab3266c9d75a69d0
|
C#
|
Sephiroth/ORMTest
|
/Linq2DB.Repository/Impl/UserRepository.cs
| 2.640625
| 3
|
using IRepository.Interface;
using LinqToDB;
using Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace Linq2DB.Repository.Impl
{
public class UserRepository : IRepository<TUserinfo>
{
public async Task<bool> AddEntity(TUserinfo t)
{
bool rs = false;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
rs = await db.InsertAsync(t) == 1;
}
return rs;
}
public async Task<bool> AddList(IList<TUserinfo> list)
{
bool rs = false;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
rs = await db.InsertAsync(list) == list.Count;
}
return rs;
}
public async Task<bool> DeleteEntity(Expression<Func<TUserinfo, bool>> predicate)
{
bool rs = false;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
rs = await db.TUserinfoes.DeleteAsync(predicate) > 0;
}
return rs;
}
public async Task<TUserinfo> GetEntity(Expression<Func<TUserinfo, bool>> predicate)
{
TUserinfo obj = null;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
obj = await db.TUserinfoes.FirstOrDefaultAsync(predicate);
}
return obj;
}
public async Task<IList<TUserinfo>> GetList(Expression<Func<TUserinfo, bool>> predicate, int firstRow, int pageSize)
{
IList<TUserinfo> list = null;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
list = await db.TUserinfoes.CreateQuery<TUserinfo>(predicate).ToListAsync();
}
return list;
}
public async Task<bool> ModifyEntity(TUserinfo t)
{
bool rs = false;
using (DbElectricityNetworkDB db = new DbElectricityNetworkDB())
{
rs = await db.UpdateAsync(t) == 1;
}
return rs;
}
}
}
|
d8bceb7d65f20845a2f847a2458cf5975e402581
|
C#
|
michael-wolfenden/Cake.Npx
|
/src/Cake.Npx/NpxSettings.cs
| 2.859375
| 3
|
using System;
using System.Collections.Generic;
using Cake.Core;
using Cake.Core.IO;
using Cake.Core.Tooling;
namespace Cake.Npx
{
/// <summary>
/// Npx tool settings.
/// </summary>
public class NpxSettings : ToolSettings
{
[Obsolete("Only need for ToolFixture constraint")]
public NpxSettings() { }
/// <summary>
/// Initializes a new instance of the <see cref="NpxSettings"/> class.
/// </summary>
/// <param name="command">Command to run</param>
/// <param name="additionalArguments">Additional arguments to pass to the command</param>
public NpxSettings(string command, ProcessArgumentBuilder additionalArguments)
{
Command = command;
AdditionalArguments = additionalArguments;
Packages = new HashSet<string>();
}
/// <summary>
/// Gets the command to be run.
/// </summary>
public string Command { get; }
/// <summary>
/// Get the additional arguments to pass to the command.
/// </summary>
public ProcessArgumentBuilder AdditionalArguments { get; }
/// <summary>
/// Gets the list of packages which should be installed.
/// </summary>
public HashSet<string> Packages { get; }
/// <summary>
/// Instruct npx not to look in $PATH, or in the current package's node_modules/.bin for an
/// existing version before deciding whether to install
/// </summary>
public bool IgnoreExisting { get; private set; }
/// <summary>
/// Suppressed any output from npx itself (progress bars, error messages, install reports).
/// Subcommand output itself will not be silenced.
/// </summary>
public bool IsQuiet { get; private set; }
/// <summary>
/// Install a package by name.
/// </summary>
/// <param name="packageName">Name of the package.</param>
/// <returns>The settings instance with <paramref name="packageName"/> added to <see cref="NpxSettings.Packages"/>.</returns>
public NpxSettings AddPackage(string packageName)
{
if (string.IsNullOrWhiteSpace(packageName))
throw new ArgumentException("Package name cannot be null or empty.", nameof(packageName));
Packages.Add(packageName);
return this;
}
/// <summary>
/// Instruct npx not to look in $PATH, or in the current package's node_modules/.bin for an
/// existing version before deciding whether to install
/// </summary>
/// <returns>The settings instance with ignore existing set.</returns>
public NpxSettings IgnoringExisting()
{
IgnoreExisting = true;
return this;
}
/// <summary>
/// Suppressed any output from npx itself (progress bars, error messages, install reports).
/// Subcommand output itself will not be silenced.
/// </summary>
/// <returns>The settings instance with quiet set.</returns>
public NpxSettings Quiet()
{
IsQuiet = true;
return this;
}
/// <summary>
/// Evaluates the settings and writes them to <paramref name="arguments"/>.
/// </summary>
/// <param name="arguments">The argument builder into which the settings should be written.</param>
public void Evaluate(ProcessArgumentBuilder arguments)
{
if (IsQuiet)
{
arguments.Append("--quiet");
}
foreach (var package in Packages)
{
arguments.AppendSwitchQuoted("-p", package);
}
if (IgnoreExisting)
{
arguments.Append("--ignore-existing");
}
arguments.Append(Command);
if (!AdditionalArguments.IsNullOrEmpty())
{
arguments.Append(AdditionalArguments.Render());
}
}
}
}
|
4d9e5253c990fe9789a9fc338d0ac6c4c3b69373
|
C#
|
Hikimon99/Portfolio
|
/In-Process Learning C# ASP MVC/Kim_InHo_HW3/Models/CateringOrder.cs
| 3.0625
| 3
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Kim_InHo_HW3.Models
{
public class CateringOrder: Order
{
//Validations for 2-4 letters and writes error messages
[Required]
[MaxLength(4, ErrorMessage = "Code must be less than 4"), MinLength(2, ErrorMessage = "Code can't be less than 2 characters")]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "Only letters please")]
public string CustomerCode { get; set; }
//Validations for delivery fee max and min.
[Required]
public Decimal _decDeliveryFee;
[Display(Name = "Delivery Fee:")]
[Range(minimum: 0, maximum: 250, ErrorMessage = "Enter 0 or a positive number up to 250")]
[DisplayFormat(DataFormatString = "{0:c}")]
public Decimal DeliveryFee
{
get { return _decDeliveryFee; }
set { _decDeliveryFee = value; }
}
//Property of Preferred Customer
[Display(Name = "Is this a preferred customer:")]
public Boolean PreferredCustomer { get; set; }
//method to set delivery fee and calculate total
public void CalcTotals(Decimal _decDeliveryFee)
{
base.CalcSubtotals();
if (PreferredCustomer)
{
DeliveryFee = 0;
}
else { DeliveryFee = _decDeliveryFee; }
base.Total = base.Subtotal + DeliveryFee;
}
}
}
|