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 |
|---|---|---|---|---|---|---|
1fb06a78c9604473b249a25ade4eec62189259e3 | C# | RamzesUAA/SortingAlgorithms | /SortingAlgorithms/AlgorithmsLibrary/Algorithms/SelectionSort.cs | 3.25 | 3 | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
namespace AlgorithmsLibrary.Algorithms
{
public class SelectionSort : SortBase
{
public void selectionSort(ref int[] arr)
{
for(int i = 0; i < arr.Length - 1; ++i)
{
int min = i;
for(int j= (i+1); j< arr.Length; ++j)
{
if(arr[min] < arr[j])
{
min = j;
}
}
Swap(ref arr[min], ref arr[i]);
}
}
}
}
|
1932e73eb28996179de6c6d048d82d19eaaf090e | C# | stanek09512/Zarzadzanie_Druzyna_Pilkarska | /Backend_Prod_Front/InzBackend/InzBackend/InzBackApi/InzBackInfrastructure/Services/MatchService.cs | 2.96875 | 3 | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using InzBackCore.Domain;
using InzBackCore.Repositories;
using InzBackInfrastructure.Commands.Matches;
using InzBackInfrastructure.DTO;
using InzBackInfrastructure.Repositories;
using System.Linq;
namespace InzBackInfrastructure.Services
{
public class MatchService : IMatchService
{
private readonly IMatchRepository _matchRepository;
private readonly IPlayerRepository _playerRepository;
private readonly IAuthRepository _authRepository;
private readonly IMapper _mapper;
public MatchService(IMatchRepository matchRepository, IMapper mapper, IPlayerRepository playerRepository, IAuthRepository authRepository)
{
_matchRepository = matchRepository;
_authRepository = authRepository;
_mapper = mapper;
_playerRepository = playerRepository;
}
public async Task<Matchh> GetAsyncMatch(int id) //metoda pobiera mecz
{
var match = await _matchRepository.GetAsyncMatch(id);
if(match == null)
{
throw new Exception($"Match with this id {id} does not exist");
}
return match;
}
public async Task<IEnumerable<Matchh>> GetAsyncMatchesFuture(int userId) //metoda pobiera mecze ktore sa zaplanowane na przyszłosc
{
//pobiera wszystkie mecze danego uzytkownika i konwertuje do listy
var matches = await _matchRepository.GetAsyncMatches(userId);
List<Matchh> matchesList = matches.ToList();
for (int i = 0; i < matchesList.Count(); i++)
{
// warunek- jezeli data jest niższa od terazniejszej to mecz zostaje usuniety z listy
DateTime? date = matchesList[i].MatchDate;
if (date < DateTime.Now)
{
matchesList.Remove(matchesList[i]);
// iteracja zostaje cofnieta o jeden element poniewaz element zostal usuniety a stos obsunąl sie o element
i--;
}
}
// sortuje liste meczy po dacie
matchesList = matchesList.OrderBy(x => x.MatchDate).ToList();
return matchesList;
}
public async Task<IEnumerable<Matchh>> GetAsyncMatchesPast(int userId) // pobiera mecze z przeszlosci
{
var matches = await _matchRepository.GetAsyncMatches(userId);
List<Matchh> matchesList = matches.ToList();
for (int i = 0; i < matchesList.Count(); i++)
{
// warunek- jezeli data jest wyzsza od terazniejszej to mecz zostaje usuniety z listy
DateTime? date = matchesList[i].MatchDate;
if (date > DateTime.Now)
{
matchesList.Remove(matchesList[i]);
i--;
}
}
// sortuje liste meczy po dacie
matchesList = matchesList.OrderBy(x => x.MatchDate).ToList();
return matchesList;
}
public async Task<IEnumerable<Matchh>> GetNearestMatch(int userId) //metoda pobiera najblizszy/najblizsze mecze
{
var matches = await GetAsyncMatchesFuture(userId);
List<Matchh> matchh = matches.ToList();
// warunek - jezeli lista nie jest pusta, sa zaplanowane jakies mecze na przyszlosc
if (matchh.Count != 0)
{
// przypisuje pierwszy obiekt z listy
Matchh nearestMatch = matchh[0];
// przechodzi przez cala liste nie liczac pierwszego elementu
for ( int i = 1; i < matchh.Count(); i++)
{
//warunek - jezeli data jest wieksza to przypisuje ta mniejsza czyli blizsza czasu terazniejszego
if (nearestMatch.MatchDate > matchh[i].MatchDate)
{
nearestMatch = matchh[i];
}
}
for (int i = 0; i < matchh.Count(); i++)
{
// warunek - jezeli znajduje sie jakas data bardziej na przyszlosc w liscie to ja usuwa, przez to ze moga byc np 2 mecze w tym samym czasie
if (nearestMatch.MatchDate < matchh[i].MatchDate)
{
matchh.Remove(matchh[i]);
i--;
}
}
return matchh;
}
return null;
}
public async Task<List<double>> GetAsyncTimeToMatchValue(int userId) //pobiera liste wartosci do obsłuzenia paska postepu czasu do najblizszego meczu
{
// deklaracja listy wynikow potrzebnych
List<double> results = new List<double>();
// pobiera najbliższy mecz
//warunek - jezeli nie ma meczu konczymy obliczenia
var matches =await GetNearestMatch(userId);
if( matches == null )
{
return null;
}
// zmienia na liste bo moga byc np 2 w tym samym czasie
List<Matchh> matchObj = matches.ToList();
// data terazniejsza - data meczu zaplanowanego
// konwertuje date tego meczu
DateTime matchDate = Convert.ToDateTime(matchObj[0].MatchDate);
// pobiera date terazniejsza
DateTime nowDate = Convert.ToDateTime(DateTime.Now);
// odejmuje date najblizszego meczu od daty terazniejszej i uzyskuje wynik, ile godzin pozostalo do meczu
TimeSpan finalResultFutureMatch = matchDate.Subtract(nowDate);
// umiesza wynik w liscie wynikow na miejscu 0
results.Add(finalResultFutureMatch.TotalHours);
// data terazniejsza - data meczu ostatniego/najbliższego przeszlego
// pobiera wszystkie mecze z przeszlosci
var matchesPast = await GetAsyncMatchesPast(userId);
List<Matchh> matchesPastList = matchesPast.ToList();
// sortuje po dacie
matchesPastList = matchesPastList.OrderBy(x => x.MatchDate).ToList();
// deklaracja zmiennej na date meczu przeszlego najblizszego
DateTime pastMatch;
TimeSpan finalResultPastMatch;
//warunek - jezeli mecze przeszle istnieja
if (matchesPastList.Count != 0)
{
// konwertuje date z ostatniego po sortowaniu czyli najblizszemu terazniejszosci
pastMatch = Convert.ToDateTime(matchesPastList[matchesPastList.Count - 1].MatchDate);
// odejmuje od daty terazniejszej date meczu przeszlego, uzyskujemy wynik czasu
finalResultPastMatch = nowDate.Subtract(pastMatch);
}
else
{
// jezeli nie ma meczu w przeszlosci to liczy od czasu terazniejszego tzn czas terazniejszy - 0
finalResultPastMatch = TimeSpan.Zero;
}
//wynik czasu data terazniejsza - mecz przeszly umieszcza na miejscu 1 w liscie
results.Add(finalResultPastMatch.TotalHours);
// wynik czasu mecz przeszly do daty terazniejszej + mecz przyszly do daty terazniejszej umieszcza na miejscu 2 w liscie
results.Add(results[0] + results[1]);
// liczy procent z czasu ile zostalo do meczu przez sume czasu od ostatniego do nastepnego i dodaje na pozycji 3 w liscie
results.Add(100-((results[0] / results[2])*100));
results[0] = Convert.ToInt32(results[0]);
return results;
}
public async Task<int> CreateAsyncMatch(CreateMatch matchData, int userId) //metoda tworzaca nowy mecz
{
var user = await _authRepository.UserAccount(userId);
//zera to wynik meczu zadeklarowane z gory
var match = new Matchh(matchData.OpponentTeam, matchData.MatchDate, matchData.Place);
match.user = user;
int matchId = await _matchRepository.AddAsyncMatch(match, userId);
return matchId;
}
public async Task UpdateAsyncMatch(int id, UpdateMatch matchData) //metoda edytujaca dane meczu
{
var match = await _matchRepository.GetAsyncMatch(id);
if (match == null)
{
throw new Exception($"Match with this id {id} does not exist");
}
match.SetNameOpponentTeam(matchData.OpponentTeam);
match.SetMatchDate(matchData.MatchDate);
match.SetPlace(matchData.Place);
match.SetScoreFirstTeam(matchData.ScoreFirstTeam);
match.SetScoreSecondTeam(matchData.ScoreSecondTeam);
await _matchRepository.UpdateAsyncMatch(match);
}
public async Task DeleteAsyncMatch(int id) // metoda usuwa mecz
{
var match = await _matchRepository.GetAsyncMatch(id);
if (match == null)
{
throw new Exception($"Match with this id {id} does not exist");
}
await _matchRepository.DeleteAsyncMatch(match);
}
public async Task AddPlayersToMatch(int MatchId, IEnumerable<int> PlayersId) // metoda dodaje zawodnikow do meczu
{
var match = await _matchRepository.GetAsyncMatch(MatchId);
if (match == null)
{
throw new Exception($"Match with this id {MatchId} does not exist");
}
//await _matchRepository.AddAsyncPlayerToMatch(MatchId,PlayersId);
var playersListInMatch = await _matchRepository.GetAsyncPlayersInMatch(MatchId);
foreach (int playerId in PlayersId) //przechodze przez wszystkie id playersow ktorych chce dodac do meczu
{
var plr2matches = new MatchhPlayer(); //deklaruje obiekt tablicy posredniej
bool IsInList = false;
IsInList = playersListInMatch.Players2Match.Exists(x => x.PlayerId == playerId); // jezeli jest juz przypisany to tu zmienia na prawde
if (IsInList == false) //dzieki temu widzimy czy nalezy jezeli falsz czyli nie to dodajemy
{
var player = await _playerRepository.GetAsyncPlayer(playerId); //pobieram zawodnika o wskazanym id
if (player == null) continue;
else
{
plr2matches.Matchh = match; //wypelniamy obiekt tabeli posredniej
plr2matches.Player = player;
await _matchRepository.AddAsyncPlayerToMatch(MatchId, plr2matches);
// match.Players2Match.Add(plr2matches);
}
}
}
await Task.CompletedTask;
}
public async Task<IEnumerable<PlayerDto>> GetPlayersInMatch(int MatchId) //pobiera liste zawodnikow w meczu, pelnych obiektow zawodnik
{
// pobiera mecz z lista zawodnikow dopisanych do niego
var playersInMatch = await _matchRepository.GetAsyncPlayersInMatch(MatchId);
if (playersInMatch == null)
{
throw new Exception($"Match with this id {MatchId} does not exist");
}
//przechodzi przez liste dopisanych zawodnikow do meczu, pobiera id nastepnie pobiera zawodnika i caly obiekt zawodnika dodaje do listy
var playerList = new List<Player>();
for (int i = 0; i < playersInMatch.Players2Match.Count; i++)
{
int playerId = Convert.ToInt32(playersInMatch.Players2Match[i].PlayerId);
var player = await _playerRepository.GetAsyncPlayer(playerId);
playerList.Add(player);
}
return _mapper.Map<IEnumerable<PlayerDto>>(playerList);
}
public async Task<IEnumerable<PlayerDto>> GetPlayersOutMatch(int Matchid, int userId)
{
//sprawdza czy mecz istnieje
var match = await _matchRepository.GetAsyncMatch(Matchid);
if (match == null)
{
throw new Exception($"Match with this id {Matchid} does not exist");
}
//pobiera wszytskich zawodnikow uzytkownika i mapuje na obiektDto a nastepnie rzutuje na liste
var allUserPlayers = await _playerRepository.GetAsyncAllPlayers(userId);
var allUserPlayersDto = _mapper.Map<IEnumerable<PlayerDto>>(allUserPlayers);
List<PlayerDto> allUserPlayersDtoList = allUserPlayersDto.ToList();
//pobiera liste zawodnikow dodanych do meczu
var playersInMatch = await GetPlayersInMatch(Matchid);
List<PlayerDto> playersInMatchList = playersInMatch.ToList();
// usuwa z listy wszystkich zawodnikow ktorzy sa w kadrze
foreach (var player in playersInMatch)
{
var plrToRemove = allUserPlayersDtoList.FirstOrDefault( x => x.Id == player.Id);
if(plrToRemove != null) allUserPlayersDtoList.Remove(plrToRemove);
}
return allUserPlayersDtoList;
}
public async Task DeletePlayersInMatch(int Matchid, IEnumerable<int> PlayersId)
{
var playersListInMatch = await _matchRepository.GetAsyncPlayersInMatch(Matchid); //pobiera mecz z zawarta lista zawodnikow przypisana do niego
if (playersListInMatch == null)
{
throw new Exception($"Match with this id {Matchid} does not exist");
}
foreach (var player in PlayersId) //rpzechodzimy kolejno po indeksach ktore wskazuja ktorych zawodnikow nie chcemy w druzynie
{
var plr = playersListInMatch.Players2Match.SingleOrDefault(x => x.PlayerId == player); //pobieramy zawdonika pod indeksem
if (plr == null) continue; // jezeli nie ma takiego to kontynuujemy
else
{
await _matchRepository.DeleteAsyncListPlayersInMatch(Matchid, plr);
}
}
await Task.CompletedTask;
}
public async Task UpdateStatsInMatch(int Matchid, IEnumerable<GetPlayersStatisticInMatchDto> PlayersStats)
{
var playersListInMatch = await _matchRepository.GetAsyncPlayersInMatch(Matchid); //pobieram mecz a w nim liste z jakimi playerami sie łączy
if (playersListInMatch == null)
{
throw new Exception($"Match with this id {Matchid} does not exist");
}
var matchhPlayer = _mapper.Map<IEnumerable<MatchhPlayer>>(PlayersStats);
List<MatchhPlayer> matchhPlayerList = matchhPlayer.ToList();
foreach (var playerS in PlayersStats)
{
var plr = playersListInMatch.Players2Match.SingleOrDefault(x => x.PlayerId == playerS.PlayerId); //pobieramy zawodnika o id
// playersListInMatch.Players2Match.Remove(plr); //usuwamy go na chwile bo nie mozna albo nie wiem jak nadpisac
await _matchRepository.DeleteAsyncListPlayersInMatch(Matchid, plr);
//deklaruje obiekt tablicy posredniej
var match = await _matchRepository.GetAsyncMatch(Matchid); //pobieram mecz o wskazanym id
var player = await _playerRepository.GetAsyncPlayer(Convert.ToInt32(playerS.PlayerId)); //pobieram zawodnika o wskazanym id
if (player != null)
{
var plr2matches = new MatchhPlayer(Convert.ToInt16(playerS.Goals), Convert.ToInt16(playerS.Assists), Convert.ToInt16(playerS.YellowCard), Convert.ToInt16(playerS.RedCard), Convert.ToBoolean(playerS.PlayInMatch), match, player);
await _matchRepository.AddAsyncPlayerStatisticToMatch(Matchid, plr2matches);
}
}
await Task.CompletedTask;
}
public async Task<IEnumerable<MergedPlayersStatisticsDto>> GetListPlayersStatistics(int Matchid) // pobiera statysyki zawodnikow w konkretnym meczu
{
var match = await _matchRepository.GetAsyncMatch(Matchid);
if (match == null)
{
throw new Exception($"Match with this id {Matchid} does not exist");
}
var playersListInMatch = await _matchRepository.GetAsyncPlayersInMatch(Matchid); //pobieram mecz a w nim liste z jakimi playerami sie łączy
var playerList = new List<MatchhPlayer>();
for (int i = 0; i < playersListInMatch.Players2Match.Count; i++)
{
var player = new MatchhPlayer(Convert.ToInt16(playersListInMatch.Players2Match[i].Goals), Convert.ToInt16(playersListInMatch.Players2Match[i].Assists), Convert.ToInt16(playersListInMatch.Players2Match[i].YellowCard), Convert.ToInt16(playersListInMatch.Players2Match[i].RedCard), Convert.ToBoolean(playersListInMatch.Players2Match[i].PlayInMatch)); //wyszukuje go
player.PlayerId = Convert.ToInt16(playersListInMatch.Players2Match[i].PlayerId); //wybieram zawodnika dopisanego do meczu
playerList.Add(player); //i dodaje go do listy
}
List<MergedPlayersStatisticsDto> AllInfoListPlrs = new List<MergedPlayersStatisticsDto>();
List<MatchhPlayer> playersSList = playerList.ToList(); // konwertuje ienumerable do listy zeby moc wykonac swoje dzialania
for(int i =0; i< playersSList.Count; i++)
{
MergedPlayersStatisticsDto playerStatsInMatchFull = new MergedPlayersStatisticsDto();
var plr = _playerRepository.GetAsyncPlayer(Convert.ToInt16(playersSList[i].PlayerId));
Player plaObj = plr.Result;
playerStatsInMatchFull.PlayerId = Convert.ToInt16(playersSList[i].PlayerId);
playerStatsInMatchFull.Name = plaObj.Name;
playerStatsInMatchFull.Surname = plaObj.Surname;
playerStatsInMatchFull.Position = plaObj.Position;
playerStatsInMatchFull.Goals = Convert.ToInt32(playersSList[i].Goals);
playerStatsInMatchFull.Assists = Convert.ToInt32(playersSList[i].Assists);
playerStatsInMatchFull.YellowCard = Convert.ToInt32(playersSList[i].YellowCard);
playerStatsInMatchFull.RedCard = Convert.ToInt32(playersSList[i].RedCard);
playerStatsInMatchFull.PlayInMatch = playersSList[i].PlayInMatch;
AllInfoListPlrs.Add(playerStatsInMatchFull);
}
//return _mapper.Map<IEnumerable<GetPlayersStatisticInMatchDto>>(playersS);
AllInfoListPlrs = SortPlayers(AllInfoListPlrs);
return AllInfoListPlrs;
}
public List<MergedPlayersStatisticsDto> SortPlayers(List<MergedPlayersStatisticsDto> Plrs) // metoda sortuje zawodnikow po pozycji
{
List<string> positions = new List<string> { "Bramkarz", "Obronca", "Pomocnik", "Napastnik" };
List<MergedPlayersStatisticsDto> FinalListPlrs = new List<MergedPlayersStatisticsDto>();
foreach (string elem in positions)
{
foreach (MergedPlayersStatisticsDto elemP in Plrs)
{
if (elemP.Position == elem)
{
FinalListPlrs.Add(elemP);
}
}
}
return FinalListPlrs;
}
}
}
|
9b436b608751a4ac394f5b3ebf82385006d487a1 | C# | lavar3l/Ewidencja | /CompanyDetails.cs | 2.734375 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ewidencja
{
public partial class CompanyDetails : Form
{
public Company companyDetails;
string companyID = "0"; // Ma znaczenie tylko przy edycji!
public CompanyDetails(bool addNew = true, Company initialData = null)
{
InitializeComponent();
if(!addNew)
{
this.labelTitle.Text = "Edytuj dane firmy";
this.Text = "Edycja danych firmy";
acceptButton.Text = "Zapisz";
companyID = initialData.companyID;
nameTextBox.Text = initialData.companyName;
NIPtextBox.Text = initialData.NIP;
streetNameTextBox.Text = initialData.streetName;
buildingNoTextBox.Text = initialData.buildingNo;
postalCodeTextBox.Text = initialData.postalCode;
cityTextBox.Text = initialData.city;
}
}
private void acceptButton_Click(object sender, EventArgs e)
{
companyDetails = new Company(companyID, nameTextBox.Text, NIPtextBox.Text, streetNameTextBox.Text, buildingNoTextBox.Text, postalCodeTextBox.Text, cityTextBox.Text);
this.DialogResult = DialogResult.OK;
this.Close();
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
}
|
9d2f4ac996dd383376e4a1f5290bb874693b25bf | C# | Ciclo-DAW/DWES | /Unidad 4/Ejercicios/Ejercicio4.2.3/Ejercicio/Models/Words.cs | 3.75 | 4 | using System.Collections.Generic;
namespace Ejercicio.Models
{
public class Words
{
private static List<string> list = new List<string>();
// permitimos acceso en modo lectura a la lista de palabras al resto de objetos de la aplicación
public List<string> List { get => list; }
// se proporciona un método para que desde el exterior puedan agregarse palabras a la lista
public void AddWord(string word)
{
if (!list.Contains(word)) // comprobamos que la lista NO contiene ya la palabra para evitar duplicados
{
list.Add(word); // añadimos la nueva palabra
list.Sort(); // ordenamos la lista (por defecto al ser cadenas se ordenará por orden alfabético)
}
}
}
}
|
196c8fc922a81b71b7161ff08c3b6b6bc9ba308c | C# | itayl13/StudiesExercises | /ex4/VendingDP.Lib/Commands/EndOrder.cs | 2.734375 | 3 | using System;
namespace VendingDP.Lib.Commands
{
public class EndOrder : Command
{
public override string CommandPrintingFormat() => "EndOrder";
public override void Run(ref Order currentOrder)
{
if (currentOrder.Price > 0)
{
currentOrder.EndOrder();
Console.WriteLine(currentOrder);
currentOrder = new Order(menu: currentOrder.Menu);
Console.WriteLine("\n" + CommandExecutor.HELLO);
}
else
{
Console.WriteLine(CommandExecutor.END_EMPTY_ORDER);
}
}
}
}
|
6839d6090202deac55598281598db8f93ea7f7e1 | C# | Oswin2014/Behavior_Tree-Practice-in-Unity | /Behavior Tree Practice/Assets/_Script/AI/Agent/Context.cs | 2.515625 | 3 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using System.Globalization;
namespace behaviac
{
public class Context
{
private static Dictionary<int, Context> ms_contexts = new Dictionary<int, Context>();
private Dictionary<string, Agent> m_namedAgents = new Dictionary<string, Agent>();
private Dictionary<string, Variables> m_static_variables = new Dictionary<string, Variables>();
int m_context_id;
//World m_world;
Context(int contextId)
{
//m_world = null;
m_context_id = contextId;
}
~Context()
{
//this.m_world = null;
//this.CleanupStaticVariables();
this.CleanupInstances();
//ms_eventInfosGlobal.Clear();
}
void CleanupInstances()
{
//foreach (KeyValuePair<string, Agent> p in m_namedAgents)
//{
// string msg = string.Format("{0}:{1}", p.Key,p.Value.GetName());
// behaviac.Debug.Log(msg);
//}
//Debug.Check(m_namedAgents.Count == 0, "you need to call DestroyInstance or UnbindInstance");
m_namedAgents.Clear();
}
public static Context GetContext(int contextId)
{
Debug.Check(contextId >= 0);
if (ms_contexts.ContainsKey(contextId))
{
Context pContext = ms_contexts[contextId];
return pContext;
}
Context pC = new Context(contextId);
ms_contexts[contextId] = pC;
return pC;
}
public Agent GetInstance(string agentInstanceName)
{
bool bValidName = !string.IsNullOrEmpty(agentInstanceName);
if (bValidName)
{
string className = null;
GetClassNameString(agentInstanceName, ref className);
if (m_namedAgents.ContainsKey(className))
{
Agent pA = m_namedAgents[className];
return pA;
}
return null;
}
return null;
}
static bool GetClassNameString(string variableName, ref string className)
{
Debug.Check(!string.IsNullOrEmpty(variableName));
int pSep = variableName.LastIndexOf(':');
if (pSep > 0)
{
Debug.Check(variableName[pSep - 1] == ':');
className = variableName.Substring(0, pSep - 1);
return true;
}
else
{
className = variableName;
return true;
}
//return false;
}
public static void LogCurrentStates()
{
}
/**
if staticClassName is no null, it is for static variable
*/
public void SetStaticVariable<VariableType>(CMemberBase pMember, string variableName, VariableType value, string staticClassName, uint variableId)
{
Debug.Check(!string.IsNullOrEmpty(variableName));
Debug.Check(!string.IsNullOrEmpty(staticClassName));
if (!m_static_variables.ContainsKey(staticClassName))
{
m_static_variables[staticClassName] = new Variables();
}
Variables variables = m_static_variables[staticClassName];
variables.Set(null, pMember, variableName, value, variableId);
}
}
} |
9ee86114595e4369cb5f7969cd8cc621d9c4bcc8 | C# | cthibault/passgen | /PasswordGenerator/PasswordGenerator.cs | 2.9375 | 3 | using PasswordGenerator.Random;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security;
using System.Security.Cryptography;
using System.Text;
namespace PasswordGenerator
{
public class PasswordGenerator
{
public PasswordGenerator(RuleSet ruleSet)
{
RuleSet = ruleSet;
}
public RuleSet RuleSet { get; }
public SecureString Generate(int length)
{
return PasswordGeneratorInteral.Generate(RuleSet, length);
}
private class PasswordGeneratorInteral
{
private PasswordGeneratorInteral(RuleSet ruleSet, int length) : this(ruleSet, length, new RandomProvider())
{ }
private PasswordGeneratorInteral(RuleSet ruleSet, int length, IRandomProvider randomProvider)
{
if (ruleSet == null)
{
throw new ArgumentNullException(nameof(ruleSet));
}
if (!ruleSet.IsValid)
{
throw new ArgumentException("Invalid Rule Set", nameof(ruleSet));
}
if (randomProvider == null)
{
throw new ArgumentNullException(nameof(randomProvider));
}
if (length < ruleSet.MinLength)
{
throw new ArgumentOutOfRangeException(nameof(length), length, $"{nameof(length)} is shorter than what is needed to meet the requirements ({ruleSet.MinLength}).");
}
Length = length;
SetResults = ruleSet.Requirements.Select(r => new CharacterSetResult(r)).ToList();
RandomProvider = randomProvider;
GeneratedPassword = new SecureString();
}
private int Length { get; }
private List<CharacterSetResult> SetResults { get; }
private IRandomProvider RandomProvider { get; }
private SecureString GeneratedPassword { get; }
public static SecureString Generate(RuleSet ruleSet, int length)
{
var generator = new PasswordGeneratorInteral(ruleSet, length);
return generator.Generate();
}
private SecureString Generate()
{
for (int i = 0; i < Length; i++)
{
GenerateNextCharacter(i, SetResults);
}
var incompleteTypes = SetResults.Where(r => r.RequirementDelta < 0);
while (incompleteTypes.Any())
{
var overCompleteType = GetNextCharTypeResult(SetResults.Where(r => r.RequirementDelta > 0));
var charIndexToReplace = overCompleteType.Indicies.ElementAt(RandomProvider.Next(overCompleteType.Indicies.Count()));
overCompleteType.RemoveIndex(charIndexToReplace);
GenerateNextCharacter(charIndexToReplace, incompleteTypes, true);
}
GeneratedPassword.MakeReadOnly();
return GeneratedPassword;
}
private void GenerateNextCharacter(int index, IEnumerable<CharacterSetResult> setResults, bool replace = false)
{
var typeResult = GetNextCharTypeResult(setResults);
char character = GetNextCharacter(typeResult.CharacterSet.Chars);
typeResult.AddIndex(index);
if (replace)
{
GeneratedPassword.SetAt(index, character);
}
else
{
GeneratedPassword.AppendChar(character);
}
}
private char GetNextCharacter(char[] characters)
{
int index = RandomProvider.Next(characters.Length);
return characters[index];
}
private CharacterSetResult GetNextCharTypeResult(IEnumerable<CharacterSetResult> setResults)
{
if (setResults == null || !setResults.Any())
{
throw new ArgumentOutOfRangeException(nameof(setResults));
}
int index = RandomProvider.Next(setResults.Count());
return setResults.ElementAt(index);
}
}
private class CharacterSetResult
{
private readonly List<int> _indicies = new List<int>();
public CharacterSetResult(CharacterSet characterSet, int minCount)
{
CharacterSet = characterSet;
MinCount = minCount;
}
public CharacterSetResult(CharacterSetRequirement requirement)
{
if (requirement == null)
{
throw new ArgumentNullException(nameof(requirement));
}
CharacterSet = requirement.CharacterSet;
MinCount = requirement.MinCount;
}
public CharacterSet CharacterSet { get; }
public int MinCount { get; }
public int RequirementDelta => _indicies.Count - MinCount;
public IEnumerable<int> Indicies => _indicies;
public void AddIndex(int index)
{
_indicies.Add(index);
}
public void RemoveIndex(int index)
{
_indicies.Remove(index);
}
}
}
} |
2776f32279af80d9d023725a3bcf4de344b86b02 | C# | chaitrashankar06/Chaitra_Repo | /LightSimulatorTesting/Program.cs | 2.53125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using System.Net.Sockets;
using TestInterface;
namespace LightSimulatorTesting
{
class Program
{
static void Main(string[] args)
{
//try
//{ // sends the text with timeout 10s
// //TestInterface.Class3.StartClient();
// while (true)
// {
// TestInterface.TestInterfaceClass OTestInterfaceClass = new TestInterfaceClass();
// OTestInterfaceClass.Init();
// Console.WriteLine("enter Command");
// string szCommand = Console.ReadLine();
// OTestInterfaceClass.Send(szCommand);
// string szresult = OTestInterfaceClass.Receive();
// Console.WriteLine(szresult);
// // TestInterface.TestInterfaceClass.client.Disconnect(true);
// }
//}
//catch (Exception ex) { /* ... */ }
//}
}
}
}
|
c22f1bd5fd6be848eafe6211ac34871eb66d4a3b | C# | irun99/hdt-deck-predictor | /DeckPredictor/Predictor.cs | 2.71875 | 3 | using Hearthstone_Deck_Tracker.Hearthstone;
using Hearthstone_Deck_Tracker;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Compression;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System;
namespace DeckPredictor
{
public class Predictor
{
private const int DeckSize = 30;
private List<Deck> _classDecks;
private List<Deck> _possibleDecks;
private int _numIgnoredCards;
private Dictionary<string, CardInfo> _possibleCards =
new Dictionary<string, CardInfo>();
private List<CardInfo> _predictedCards;
private List<CardInfo> _nextPredictedCards;
private IOpponent _opponent;
private bool _classDetected;
private CardProximityRanker _proximityRanker;
public Predictor(IOpponent opponent, ReadOnlyCollection<Deck> metaDecks)
{
Log.Debug("Copying possible decks from the meta");
_classDecks = new List<Deck>(metaDecks);
_possibleDecks = new List<Deck>(metaDecks);
_opponent = opponent;
CheckOpponentClass();
CheckOpponentMana();
}
// We always show a card at this probability or higher.
public decimal ProbabilityAlwaysInclude { get; set; } = .65m;
// We show a card at this probability if the opponent has enough mana to play them.
public decimal ProbabilityIncludeIfPlayable { get; set; } = .50m;
// We show a card at this probability if the opponent could play it and spend all their mana.
public decimal ProbabilityIncludeIfOptimal { get; set; } = .30m;
public int AvailableMana { get; private set; } = 0;
public int AvailableManaWithCoin { get; private set; } = 0;
public ReadOnlyCollection<Deck> PossibleDecks =>
new ReadOnlyCollection<Deck>(_possibleDecks);
// List of all possible cards that could be in the opponent's deck
public ICollection<CardInfo> PossibleCards => _possibleCards.Values;
// Sorted list of most likeley cards to be in opponent's deck, under the deck limit.
public List<CardInfo> PredictedCards => new List<CardInfo>(_predictedCards);
// Sorted list of the next most likely cards not in the current prediction.
public ReadOnlyCollection<CardInfo> GetNextPredictedCards(int numCards) =>
new ReadOnlyCollection<CardInfo>(_nextPredictedCards.Take(numCards).ToList());
// Returns null if the given card and copyCount have no chance to be in the opponent's deck.
public CardInfo GetPredictedCard(Card card, int copyCount)
{
string key = CardInfo.Key(card, copyCount);
return GetPredictedCard(key);
}
public CardInfo GetPredictedCard(string key)
{
if (_possibleCards.ContainsKey(key))
{
return _possibleCards[key];
}
return null;
}
private int PredictionSize => DeckSize - _numIgnoredCards;
public void CheckOpponentClass()
{
if (_classDetected)
{
return;
}
if (string.IsNullOrEmpty(_opponent.Class))
{
return;
}
// Only want decks for the opponent's class.
_classDetected = true;
_classDecks = _possibleDecks.Where(x => x.Class == _opponent.Class).ToList();
_proximityRanker = new CardProximityRanker(_classDecks);
_possibleDecks = new List<Deck>(_classDecks);
Log.Info(_possibleDecks.Count + " possible decks for class " + _opponent.Class);
UpdatePredictedCards();
}
public void CheckOpponentCards()
{
if (!_classDetected)
{
Log.Warn("Cannot CheckOpponentCards before opponent class has been detected");
return;
}
// For prediction, we only care about cards that could have started in the opponent's deck.
var knownCards = _opponent.KnownCards.Where(card => !card.IsCreated && card.Collectible).ToList();
bool hasNewRanking = _proximityRanker.UpdateCards(knownCards);
if (!hasNewRanking)
{
return;
}
_possibleDecks = new List<Deck>(_classDecks);
// Go through each ranked card and filter the decks down.
var rankedCards = _proximityRanker.RankedCards;
_numIgnoredCards = rankedCards.Count;
foreach (Card orderedCard in rankedCards)
{
var possibleDecks = _possibleDecks.Where(possibleDeck =>
{
var cardInPossibleDeck =
possibleDeck.Cards.FirstOrDefault(x => x.Id == orderedCard.Id);
return cardInPossibleDeck != null && orderedCard.Count <= cardInPossibleDeck.Count;
}).ToList();
// If this card filters possible decks down to zero, back up and ignore the remaining cards.
// Those cards will be considered "off-meta".
if (possibleDecks.Count == 0)
{
break;
}
_numIgnoredCards--;
_possibleDecks = possibleDecks;
}
UpdatePredictedCards();
}
public void CheckOpponentMana()
{
var availableMana = _opponent.GetAvailableManaNextTurn(false);
var availableManaWithCoin = _opponent.GetAvailableManaNextTurn(true);
if (availableMana != -1 &&
(availableMana != AvailableMana || availableManaWithCoin != AvailableManaWithCoin))
{
Log.Info("Updating Opponent's available mana to " + availableMana +
"(" + availableManaWithCoin + ")");
AvailableMana = availableMana;
AvailableManaWithCoin = availableManaWithCoin;
if (_classDetected)
{
UpdatePredictedCards();
}
}
}
private void UpdatePredictedCards()
{
// Determine which cards are possible.
_possibleCards.Clear();
foreach (Deck deck in _possibleDecks)
{
foreach (Card card in deck.Cards)
{
for (int copyCount = 1; copyCount <= card.Count; copyCount++)
{
var key = CardInfo.Key(card, copyCount);
if (!_possibleCards.ContainsKey(key))
{
var predictedCard = new CardInfo(card, copyCount, _possibleDecks.Count);
_possibleCards[key] = predictedCard;
}
_possibleCards[key].IncrementNumOccurrences();
}
}
}
// Prediction
// First sort possible cards by probability
var sortedPossibleCards = _possibleCards.Values
.OrderByDescending(predictedCard => predictedCard.Probability)
.ThenBy(predictedCard => predictedCard.Card.Cost)
.ThenBy(predictedCard => predictedCard.Card.Name)
.ToList();
// If our list is greater than the PredictionSize, find the probability of the first card that
// won't make the cut. All other cards have to be strictly greater than that probability.
// We do this so none of the top 30 are there for an arbitrary reason.
decimal insufficientProbability = sortedPossibleCards.Count > PredictionSize
? sortedPossibleCards.ElementAt(PredictionSize).Probability
: 0;
_predictedCards = sortedPossibleCards
.TakeWhile(predictedCard => predictedCard.Probability > insufficientProbability &&
predictedCard.Probability >= ProbabilityAlwaysInclude)
.ToList();
// Now go through the remaining possible cards to fill out the deck with speculative picks.
decimal lastPickProbability = 1;
_nextPredictedCards = new List<CardInfo>();
sortedPossibleCards.Skip(_predictedCards.Count).ToList().ForEach(possibleCard =>
{
// A speculative card is only added if its probability is high enough and it passes
// the check based on the opponent's available mana.
// Cards are playable if they are less than or equal to available mana.
// Cards are optimal if they are equal to available mana with and without the coin.
bool isPlayable = possibleCard.Card.Cost <= AvailableManaWithCoin;
bool playableCheck = isPlayable &&
possibleCard.Probability >= ProbabilityIncludeIfPlayable;
bool isOptimal = (possibleCard.Card.Cost == AvailableMana ||
possibleCard.Card.Cost == AvailableManaWithCoin);
bool optimalCheck = isOptimal &&
possibleCard.Probability >= ProbabilityIncludeIfOptimal;
// Go until the deck is filled, but allow in all valid cards at the same probability.
if ((playableCheck || optimalCheck) &&
(_predictedCards.Count < PredictionSize ||
possibleCard.Probability >= lastPickProbability))
{
_predictedCards.Add(possibleCard);
lastPickProbability = possibleCard.Probability;
}
else
{
_nextPredictedCards.Add(possibleCard);
}
});
_predictedCards = _predictedCards
.OrderBy(predictedCard => predictedCard.Card.Cost)
.ThenBy(predictedCard => predictedCard.Card.Name)
.ToList();
Log.Debug("Target prediction size: " + PredictionSize);
Log.Debug(_possibleCards.Count + " possible cards");
Log.Debug(_predictedCards.Count + " predicted cards");
}
public class CardInfo
{
private int _numOccurrences;
private int _numPossibleDecks;
public CardInfo(Card card, int copyCount, int numPossibleDecks)
{
Card = card;
CopyCount = copyCount;
_numOccurrences = 0;
_numPossibleDecks = numPossibleDecks;
}
public Card Card { get; }
// Track each copy of a card separately in the deck.
// This is 1-indexed to mirror Card.Count
public int CopyCount { get; }
public void IncrementNumOccurrences()
{
_numOccurrences++;
}
public decimal Probability => (decimal)_numOccurrences / _numPossibleDecks;
public string Key() => Key(Card, CopyCount);
public static string Key(Card card, int copyCount) => card.Id + copyCount;
}
}
}
|
ceea540e23864136ee3ac01de345c8de4dd3dc90 | C# | rediarisa/PierresBakery | /Bakery/Models/Pastry.cs | 3.03125 | 3 | using System;
namespace Bakery.Models
{
public class Pastry
{
public int Cost { get; set; }
public int Quant { get; set; }
public Pastry(int cost, int quant)
{
Cost = cost;
Quant = quant;
}
public static int PastryCost(int quant)
{
int newQuant = quant % 3;
int total = newQuant * 2;
if (quant > 2)
{
int deal = quant / 3; //every third pastry is free
total += deal * 5;
}
return total;
}
}
} |
a406e9019e7da72edefeaaec8235ad16ae71204d | C# | PPFTech/PpfChallenge002 | /PpfChallenge002/Level1/FormMp3Player.cs | 2.734375 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PpfChallenge002.Level1
{
public partial class FormMp3Player : Form
{
/// <summary>
/// コンストラクタ
/// </summary>
public FormMp3Player()
{
InitializeComponent();
}
#region "イベント"
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMp3Player_Load(object sender, EventArgs e)
{
InitForm();
}
/// <summary>
/// [...]ボタン
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSelectPath_Click(object sender, EventArgs e)
{
// ファイル選択
string filepath = SelectMp3File(textFilepath.Text);
// 選択されたファイルパスを画面に反映
if (filepath != "")
textFilepath.Text = filepath;
}
/// <summary>
/// [再生]ボタン
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonPlay_Click(object sender, EventArgs e)
{
// ここに再生の処理を書いていくよ。
}
/// <summary>
/// [停止]ボタン
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonStop_Click(object sender, EventArgs e)
{
// ここに停止の処理を書いていくよ。
}
#endregion
#region "メソッド"
/// <summary>
/// フォーム初期化
/// </summary>
private void InitForm()
{
textFilepath.Text = "";
}
/// <summary>
/// ファイル選択
/// </summary>
/// <param name="initfile">初期選択ファイルパス</param>
/// <returns>選択されたファイルのパス</returns>
private string SelectMp3File(string initfile)
{
string selectedfile = "";
// ファイル選択ダイアログ設定
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "mp3ファイル(*.mp3)|*.mp3";
dlg.AddExtension = true;
dlg.CheckFileExists = true;
dlg.FileName = initfile;
// ダイアログ表示
DialogResult dr = dlg.ShowDialog(this);
// OK時、選択されたファイルへのパスを取得
if (dr == DialogResult.OK)
selectedfile = dlg.FileName;
// 破棄
dlg.Dispose();
return selectedfile;
}
#endregion
}
}
|
b5475a383c29c0da19eac166687f80bb5cb94c48 | C# | sigmalin/Institute | /Assets/CardFlip/Tools/TweenVector2.cs | 2.859375 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TweenVector2
{
Vector2 src;
Vector2 dst;
float time;
float elapsed;
public TweenVector2()
{
src = Vector2.zero;
dst = Vector2.zero;
time = 0f;
elapsed = 0f;
}
public TweenVector2 Get(Vector2 _value)
{
src = _value;
elapsed = 0f;
return this;
}
public TweenVector2 To(Vector2 _value, float _time)
{
dst = _value;
time = _time;
return this;
}
public Vector2 Move(float _delta)
{
if (time <= 0f) return dst;
elapsed = Mathf.Min(elapsed + _delta, time);
float t = elapsed / time;
return Vector2.Lerp(src, dst, t*t);
}
}
|
213f24244beb54a86fe72fe48f843bb181929b6c | C# | shendongnian/download4 | /code8/1447663-39490485-127073537-2.cs | 2.984375 | 3 | public class TextBoxBehaviors
{
public static bool GetEnforceFocus(DependencyObject obj)
{
return (bool)obj.GetValue(EnforceFocusProperty);
}
public static void SetEnforceFocus(DependencyObject obj, bool value)
{
obj.SetValue(EnforceFocusProperty, value);
}
// Using a DependencyProperty as the backing store for EnforceFocus. This enables animation, styling, binding, etc...
public static readonly DependencyProperty EnforceFocusProperty =
DependencyProperty.RegisterAttached("EnforceFocus", typeof(bool), typeof(TextBoxBehaviors), new PropertyMetadata(false,
(o, e) =>
{
bool newValue = (bool)e.NewValue;
if (!newValue) return;
TextBox tb = o as TextBox;
if (tb == null)
{
MessageBox.Show("Target object should be typeof TextBox only. Execution has been seased", "TextBoxBehaviors warning",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
tb.TextChanged += OnTextChanged;
}));
private static void OnTextChanged(object o, TextChangedEventArgs e)
{
TextBox tb = o as TextBox;
tb.Focus();
/* You have to place your caret at the end of your text manually, because each focus repalce your caret at the beging of text.*/
tb.CaretIndex = tb.Text.Length;
}
}
|
340d6ca3af2fca0e716c5fc35f30c5443e3a00cd | C# | sanoojps/notifierElite | /notifierElite/SchedulerForm.cs | 2.546875 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace notifierElite
{
public partial class SchedulerForm : Form
{
public SchedulerForm()
{
InitializeComponent();
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
this.Dispose();
}
private void Save_Schedule_Click(object sender, EventArgs e)
{
string dateTimePickerText = dateTimePicker1.Text.ToString();
string dateTimePickerTimeText = dateTimePicker2.Text.ToString();
string checkedRadioButton = "";
if (radioButtonMonthly.Checked == true)
{
checkedRadioButton = radioButtonMonthly.Text;
}
if (radioButtonWeekly.Checked == true)
{
checkedRadioButton = radioButtonWeekly.Text;
}
if (radioButtonDaily.Checked == true)
{
checkedRadioButton = radioButtonDaily.Text;
}
if (radioButtonDateOfChoice.Checked == true)
{
checkedRadioButton = radioButtonDateOfChoice.Text;
}
//MessageBox.Show("Date : " + dateTimePickerText + " " + "\nTime : " + dateTimePickerTimeText + "\nSchedule Chosen : " + checkedRadioButton.ToUpper());
Schedule.Text = "Date : " + dateTimePickerText + " " + " Time : " + dateTimePickerTimeText + "\n\nSchedule Chosen :" + checkedRadioButton.ToUpper();
}
private void Save_Schedule_MouseEnter(object sender, EventArgs e)
{
this.Save_Schedule.Cursor = System.Windows.Forms.Cursors.Hand;
//this.Save_Schedule.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))),
// ((int)(((byte)(114)))), ((int)(((byte)(198)))));
this.Save_Schedule.FlatStyle = FlatStyle.Popup;
}
private void Save_Schedule_MouseLeave(object sender, EventArgs e)
{
this.Save_Schedule.Cursor = System.Windows.Forms.Cursors.Default;
//this.Save_Schedule.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))),
// ((int)(((byte)(64)))), ((int)(((byte)(66)))));
this.Save_Schedule.FlatStyle = FlatStyle.Flat;
}
private void Exit_MouseEnter(object sender, EventArgs e)
{
this.Exit.Cursor = System.Windows.Forms.Cursors.Hand;
//this.Exit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))),
// ((int)(((byte)(114)))), ((int)(((byte)(198)))));
this.Exit.FlatStyle = FlatStyle.Popup;
}
private void Exit_MouseLeave(object sender, EventArgs e)
{
this.Exit.Cursor = System.Windows.Forms.Cursors.Default;
//this.Exit.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(65)))),
// ((int)(((byte)(64)))), ((int)(((byte)(66)))));
this.Exit.FlatStyle = FlatStyle.Flat;
}
}
}
|
7df544038cd797760950dbb6edb8c8fc80b5f3df | C# | jeffman/RopeSnake | /RopeSnake/Mother3/Text/JapaneseCharacterMap.cs | 2.828125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ForwardLookup = System.Collections.Generic.Dictionary<short, char>;
using ReverseLookup = System.Collections.Generic.Dictionary<char, short>;
namespace RopeSnake.Mother3.Text
{
public class JapaneseCharacterMap : ICharacterMap
{
internal protected Dictionary<CharacterContext, ForwardLookup> _forwardLookups;
internal protected Dictionary<CharacterContext, ReverseLookup> _reverseLookups;
internal JapaneseCharacterMap(ForwardLookup normalLookup, ForwardLookup saturnLookup)
{
_forwardLookups = new Dictionary<CharacterContext, ForwardLookup>();
_reverseLookups = new Dictionary<CharacterContext, ReverseLookup>();
(var forward, var reverse) = ConfigureLookups(normalLookup);
_forwardLookups[CharacterContext.Normal] = forward;
_reverseLookups[CharacterContext.Normal] = reverse;
(forward, reverse) = ConfigureLookups(saturnLookup);
_forwardLookups[CharacterContext.Saturn] = forward;
_reverseLookups[CharacterContext.Saturn] = reverse;
}
internal (ForwardLookup forward, ReverseLookup reverse) ConfigureLookups(ForwardLookup lookup)
{
var forward = new ForwardLookup();
var reverse = new ReverseLookup();
foreach (var kv in lookup)
{
forward.Add(kv.Key, kv.Value);
if (!reverse.ContainsKey(kv.Value))
reverse.Add(kv.Value, kv.Key);
}
return (forward, reverse);
}
public virtual char Decode(short value, CharacterContext context)
{
if (_forwardLookups[context].TryGetValue(value, out char decoded))
return decoded;
return '?';
}
public virtual short Encode(char ch, CharacterContext context)
=> _reverseLookups[context][ch];
public CharacterContext GetContext(short value)
{
if (_forwardLookups[CharacterContext.Normal].ContainsKey(value))
return CharacterContext.Normal;
else if (_forwardLookups[CharacterContext.Saturn].ContainsKey(value))
return CharacterContext.Saturn;
return CharacterContext.None;
}
public bool IsSharedCharacter(char ch)
=> _reverseLookups[CharacterContext.Normal].ContainsKey(ch)
&& _reverseLookups[CharacterContext.Saturn].ContainsKey(ch);
}
}
|
5f3c239f7417257852c4f8e9a4ba9a8416d0eae5 | C# | mgulsoy/nuve | /nuve/Sentence/SentenceSegmenterEvaluator.cs | 2.90625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
namespace Nuve.Sentence
{
/// <summary>
/// Evaluates the accuracy of a SentenceSegmenter on a paragraph.
/// </summary>
internal static class SentenceSegmenterEvaluator
{
public static IEnumerable<DetailedEvaluation> Evaluate(this SentenceSegmenter segmenter,
IEnumerable<string> taggedParagraphs,
string tag = "#")
{
var evaluations = new List<DetailedEvaluation>();
foreach (string taggedParagraph in taggedParagraphs)
{
evaluations.Add(Evaluate(segmenter, taggedParagraph));
}
return evaluations;
}
public static DetailedEvaluation Evaluate(this SentenceSegmenter segmenter, string taggedParagraph,
string tag = "#")
{
IEnumerable<int> realIndices = GetBoundaryIndices(taggedParagraph, tag);
string untaggedParagraph = taggedParagraph.Replace(tag, "");
return Evaluate(segmenter, untaggedParagraph, realIndices);
}
public static DetailedEvaluation Evaluate(this SentenceSegmenter segmenter, string paragraph,
IEnumerable<int> realBoundaryIndices)
{
IEnumerable<int> predictedIndices = segmenter.GetBoundaryIndices(paragraph);
// ReSharper disable PossibleMultipleEnumeration
IEnumerable<int> misses = realBoundaryIndices.Except(predictedIndices);
IEnumerable<int> falseAlarms = predictedIndices.Except(realBoundaryIndices);
IEnumerable<int> hits = realBoundaryIndices.Intersect(predictedIndices);
// ReSharper restore PossibleMultipleEnumeration
int eosCandidateCount = GetEosCharCount(segmenter.EosCandidates, paragraph);
return new DetailedEvaluation(hits, misses, falseAlarms, eosCandidateCount, paragraph);
}
private static int GetEosCharCount(IEnumerable<char> eosCandidates, string paragraph)
{
int count = paragraph.Count(c => eosCandidates.Contains(c));
return count == 0 ? 1 : count;
}
public static IEnumerable<int> GetBoundaryIndices(string paragraph, string tag)
{
int index = -1;
int sharpCount = 0;
var boundaries = new List<int>();
while (true)
{
index = paragraph.IndexOf(tag, index + 1, StringComparison.Ordinal);
if (index != -1)
{
sharpCount++;
boundaries.Add(index - sharpCount);
}
else
{
break;
}
}
return boundaries;
}
public static void GetTotalReport(IEnumerable<DetailedEvaluation> evaluations, bool printHits = false,
bool printMisses = false, bool printFalseAlarms = false)
{
int totalEos = 0;
int totalMisses = 0;
int totalHits = 0;
int totalFalseAlarms = 0;
foreach (DetailedEvaluation evaluation in evaluations)
{
totalEos += evaluation.EosCount;
totalHits += evaluation.Hit;
totalMisses += evaluation.Missed;
totalFalseAlarms += evaluation.FalseAlarm;
if (printHits)
{
evaluation.PrintFalseAlarms();
}
if (printMisses)
{
evaluation.PrintMisses();
}
if (printFalseAlarms)
{
evaluation.PrintFalseAlarms();
}
}
var totalEval = new SimpleEvaluation(totalHits, totalMisses, totalFalseAlarms, totalEos);
Console.WriteLine(totalEval);
}
internal class Result
{
public int Missed { set; get; }
public int FalseAlarm { set; get; }
protected bool Equals(Result other)
{
return Missed == other.Missed && FalseAlarm == other.FalseAlarm;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Result) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Missed*397) ^ FalseAlarm;
}
}
}
}
} |
feb9dc2f00d23da4044b75a11e2e5ed979bb2096 | C# | yuka1984/DurableFunctionsTutorial | /Tutorial/Tutorial3/Sample.cs | 2.609375 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
namespace Tutorial3
{
public class SampleOrchestratorFunctions
{
[FunctionName(nameof(SampleOrchestratorFunction))]
public async Task<int> SampleOrchestratorFunction([OrchestrationTrigger]DurableOrchestrationContextBase durable)
{
var input = durable.GetInput<int>();
var twoXTask = durable.CallActivityAsync<int>(nameof(ActivityFunctions.ActivityNumber2x), input);
var tenXTask = durable.CallActivityAsync<int>(nameof(ActivityFunctions.ActivityNumber10x), input);
var results = await Task.WhenAll(new[] {twoXTask, tenXTask});
return results.Sum();
}
}
}
|
8054438a083b55caeb81f25e542f39b10d7993cf | C# | vitalityyy/My3d | /Matchlab/Vector3d.cs | 3.265625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace My3d
{
public class Vector3d
{
public double dx;
public double dy;
public double dz;
public Vector3d(double dx, double dy, double dz)
{
this.dx = dx;
this.dy = dy;
this.dz = dz;
}
public static Vector3d operator +(Vector3d v0, Vector3d v1)
{
return new Vector3d(v0.dx + v1.dx, v0.dy + v1.dy, v0.dz + v1.dz);
}
public static Vector3d operator -(Vector3d v0, Vector3d v1)
{
return new Vector3d(v0.dx - v1.dx, v0.dy - v1.dy, v0.dz - v1.dz);
}
public static Vector3d operator *(Vector3d v0, Vector3d v1)
{
return new Vector3d(v0.dx * v1.dx, v0.dy * v1.dy, v0.dz * v1.dz);
}
public static Vector3d operator /(Vector3d v0, Vector3d v1)
{
return new Vector3d(v0.dx / v1.dx, v0.dy / v1.dy, v0.dz / v1.dz);
}
}
}
|
0d1b93061152b075385b55eb9933cdfef960d263 | C# | yongzhao1/DecompliedDotNetLibraries | /System.Data/System/Data/SqlClient/SqlServerEscapeHelper.cs | 2.828125 | 3 | namespace System.Data.SqlClient
{
using System;
using System.Data.Common;
using System.Text;
internal static class SqlServerEscapeHelper
{
internal static string EscapeIdentifier(string name)
{
return ("[" + name.Replace("]", "]]") + "]");
}
internal static void EscapeIdentifier(StringBuilder builder, string name)
{
builder.Append("[");
builder.Append(name.Replace("]", "]]"));
builder.Append("]");
}
internal static string EscapeStringAsLiteral(string input)
{
return input.Replace("'", "''");
}
internal static string MakeStringLiteral(string input)
{
if (ADP.IsEmpty(input))
{
return "''";
}
return ("'" + EscapeStringAsLiteral(input) + "'");
}
}
}
|
cbbff17790d34bb25d010d35d38b8b882849953d | C# | macuistin/ApiSwaggerAuthScan | /ApiSwaggerAuth.CLI/SwaggerScan.cs | 2.984375 | 3 | using System;
using System.Diagnostics;
using System.Net;
using System.Threading.Tasks;
using ApiSwaggerAuth.Domain.Entities;
using ApiSwaggerAuth.Domain.Services;
namespace ApiSwaggerAuth.Console
{
public class SwaggerScan : ISwaggerScan
{
private readonly IApiService _apiService;
public SwaggerScan(IApiService apiService)
{
_apiService = apiService;
}
public async Task ScanAndOutputResponse(string url)
{
var stopwatch = Stopwatch.StartNew();
LogInfo($"Scanning {url}");
var data = await _apiService.GetAsync(url);
if (data == null)
{
LogInfo("... What happened?");
}
await OutputDataAsync(data);
stopwatch.Stop();
LogInfo($"*** Completed in {stopwatch.Elapsed:g} ***\n");
}
private static async Task OutputDataAsync(ApiData data)
{
LogInfo($"Current Status: {data.Status}\tProbe Status: {data.ProbeStatus}");
if (data.ProbeStatus == HttpStatusCode.OK)
{
LogInfo("Swagger Docs:");
await foreach (var swaggerResult in data.SwaggerResults)
{
LogInfo($"\t{swaggerResult.Url} : [{swaggerResult.Name}]\n\t\tOperations:");
await foreach (var methodResult in swaggerResult.MethodProbeResults)
{
var message = $"\t\t{methodResult.StatusCode} :\t[{methodResult.Verb}]\t{methodResult.Path}";
switch (methodResult.StatusCode)
{
case HttpStatusCode.Unauthorized:
LogInfo(message);
break;
case HttpStatusCode.OK:
LogError(message);
break;
default:
LogWarning(message);
break;
}
}
}
}
}
private static void LogInfo(string message)
{
System.Console.BackgroundColor = ConsoleColor.Black;
System.Console.ForegroundColor = ConsoleColor.White;
System.Console.WriteLine($"[INFO] {message}");
}
private static void LogWarning(string message)
{
System.Console.BackgroundColor = ConsoleColor.Black;
System.Console.ForegroundColor = ConsoleColor.Yellow;
System.Console.WriteLine($"[WARN] {message}");
}
private static void LogError(string message)
{
System.Console.BackgroundColor = ConsoleColor.Black;
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine($"[ERR] {message}");
}
}
}
|
342cd84af1ff8699db84253791e047d830dc6a8a | C# | ctzuchiang/project-euler | /LeetCode/Solution/Solution/Easy/051_100/E70_ClimbingStairs.cs | 3.046875 | 3 | namespace Solution.Easy._051_100
{
public class E70_ClimbingStairs
{
public int ClimbStairs(int n)
{
int a = 1, b = 1;
while (n-- > 0)
a = (b += a) - a;
return a;
}
}
}
|
dc592eb90cb765558768eb2ff751c09c4d0563d6 | C# | gchristo/EmuladorAtari | /Atari/Chip8Commands/BaseCommand.cs | 2.640625 | 3 | namespace Emulator.Chip8Commands
{
public abstract class BaseCommand
{
protected Chip8 Chip;
public BaseCommand(Chip8 chip)
{
Chip = chip;
}
public ushort PC
{
get { return Chip.PC; }
set { Chip.PC = value; }
}
public ushort I
{
get { return Chip.I; }
set { Chip.I = value; }
}
public byte[] V
{
get { return Chip.V; }
set { Chip.V = value; }
}
public ushort[] Stack
{
get { return Chip.Stack; }
set { Chip.Stack = value; }
}
public byte SP
{
get { return Chip.SP; }
set { Chip.SP = value; }
}
public ushort Timer_Delay
{
get { return Chip.Timer_Delay; }
set { Chip.Timer_Delay = value; }
}
public abstract void Execute();
}
}
|
efbaeb517c47550b07903ee9c56dddf381cbd92a | C# | anluu275/Gacha_Roll_Tracker | /Code_Behind/Arknight_Roll_Tracker/MainWindowViewModel.cs | 2.78125 | 3 | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
namespace Arknight_Roll_Tracker
{
public class MainWindowViewModel : BaseViewModel
{
private float _curTotalRolls;
private float _amtOf6Stars;
private float _amtOf5Stars;
private float _amtOf4Stars;
private float _amtOf3Stars;
private float _percent6star;
private float _percent5star;
private float _percent4star;
private float _percent3star;
private ICommand _saveCurrentCommand;
private ICommand _saveGrandCommand;
private ICommand _addCommand;
private ICommand _subtractCommand;
public MainWindowViewModel()
{
LoadFunction();
}
#region Properties
public float CurTotalRolls
{
get
{
return _curTotalRolls;
}
set
{
_curTotalRolls = value;
OnPropertyChanged(nameof(CurTotalRolls));
}
}
public float AmtOf6Stars
{
get
{
return _amtOf6Stars;
}
set
{
_amtOf6Stars = value;
OnPropertyChanged(nameof(AmtOf6Stars));
SumforCurRolls();
PercentCalculation();
}
}
public float AmtOf5Stars
{
get
{
return _amtOf5Stars;
}
set
{
_amtOf5Stars = value;
OnPropertyChanged(nameof(AmtOf5Stars));
SumforCurRolls();
PercentCalculation();
}
}
public float AmtOf4Stars
{
get
{
return _amtOf4Stars;
}
set
{
_amtOf4Stars = value;
OnPropertyChanged(nameof(AmtOf4Stars));
SumforCurRolls();
PercentCalculation();
}
}
public float AmtOf3Stars
{
get
{
return _amtOf3Stars;
}
set
{
_amtOf3Stars = value;
OnPropertyChanged(nameof(AmtOf3Stars));
SumforCurRolls();
PercentCalculation();
}
}
public float Percent6star
{
get
{
return _percent6star;
}
set
{
_percent6star = value;
OnPropertyChanged(nameof(Percent6star));
}
}
public float Percent5star
{
get
{
return _percent5star;
}
set
{
_percent5star = value;
OnPropertyChanged(nameof(Percent5star));
}
}
public float Percent4star
{
get
{
return _percent4star;
}
set
{
_percent4star = value;
OnPropertyChanged(nameof(Percent4star));
}
}
public float Percent3star
{
get
{
return _percent3star;
}
set
{
_percent3star = value;
OnPropertyChanged(nameof(Percent3star));
}
}
#endregion Properties
#region Functions
public void SumforCurRolls()
{
CurTotalRolls = _amtOf3Stars + _amtOf4Stars + _amtOf5Stars + _amtOf6Stars;
}
public void PercentCalculation()
{
Percent6star = divide(_amtOf6Stars, _curTotalRolls) * 100;
Percent5star = divide(_amtOf5Stars, _curTotalRolls) * 100;
Percent4star = divide(_amtOf4Stars, _curTotalRolls) * 100;
Percent3star = divide(_amtOf3Stars, _curTotalRolls) * 100;
}
public float divide(float n1, float n2)
{
/* n1 divided by n2 */
if (n2 == 0)
{
return (n1 / 1);
}
return (n1 / n2);
}
private void LoadFunction()
{
try
{
using (FileStream file = new FileStream(@"ArknightCurrentRollTracker.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using var sr = new StreamReader(file);
string line = sr.ReadLine(); //read headers
line = sr.ReadLine(); // read values
if (line == null)
{
_amtOf6Stars = 0;
_amtOf5Stars = 0;
_amtOf4Stars = 0;
_amtOf3Stars = 0;
}
else
{
string[] words = line.Split(",");
_amtOf6Stars = float.Parse(words[1]);
_amtOf5Stars = float.Parse(words[2]);
_amtOf4Stars = float.Parse(words[3]);
_amtOf3Stars = float.Parse(words[4]);
}
file.Close();
}
}
catch (Exception ex)
{
throw new ApplicationException("Failed to Load File.", ex);
}
CurTotalRolls = _amtOf3Stars + _amtOf4Stars + _amtOf5Stars + _amtOf6Stars;
PercentCalculation();
try
{
using (FileStream file = new FileStream(@"ArknightGrandRollTracker.csv", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
file.Close();
}
}
catch (Exception ex)
{
throw new ApplicationException("Making Grand File Error", ex);
}
}
#endregion Functions
#region Commands
public ICommand AddCommand
{
get
{
if (_addCommand == null)
{
_addCommand = new DoCommand<string>(AddFunction);
}
return _addCommand;
}
}
private void AddFunction(string viewparam)
{
if (viewparam == "6star")
AmtOf6Stars += 1;
else if (viewparam == "5star")
AmtOf5Stars += 1;
else if (viewparam == "4star")
AmtOf4Stars += 1;
else if (viewparam == "3star")
AmtOf3Stars += 1;
}
public ICommand SubtractCommand
{
get
{
if (_subtractCommand == null)
{
_subtractCommand = new DoCommand<string>(SubtractFunction);
}
return _subtractCommand;
}
}
private void SubtractFunction(string viewparam)
{
if (viewparam == "6star")
AmtOf6Stars = AmtOf6Stars > 0 ? AmtOf6Stars -= 1 : AmtOf6Stars;
else if (viewparam == "5star")
AmtOf5Stars = AmtOf5Stars > 0 ? AmtOf5Stars -= 1 : AmtOf5Stars;
else if (viewparam == "4star")
AmtOf4Stars = AmtOf4Stars > 0 ? AmtOf4Stars -= 1 : AmtOf4Stars;
else if (viewparam == "3star")
AmtOf3Stars = AmtOf3Stars > 0 ? AmtOf3Stars -= 1 : AmtOf3Stars;
}
public ICommand SaveCurrentCommand
{
get
{
if (_saveCurrentCommand == null)
{
_saveCurrentCommand = new DoCommand(SaveCurrentFunction);
}
return _saveCurrentCommand;
}
}
public void SaveCurrentFunction()
{
try
{
DateTime dateTime = DateTime.Now;
using (StreamWriter file = new StreamWriter(@"ArknightCurrentRollTracker.csv", false))
{
file.WriteLine("Date,6* Operator,5* Operator,4* Operator,3* Operator");
file.WriteLine(dateTime.ToString("dd/MMMM/ yyyy") + "," + _amtOf6Stars + "," + _amtOf5Stars + "," + _amtOf4Stars + "," + _amtOf3Stars);
file.Close();
}
}
catch (Exception ex)
{
throw new ApplicationException("Failed to Save File.", ex);
}
}
public ICommand SaveGrandCommand
{
get
{
if (_saveGrandCommand == null)
{
_saveGrandCommand = new DoCommand(SaveGrandFunction);
}
return _saveGrandCommand;
}
}
public void SaveGrandFunction()
{
try
{
DateTime dateTime = DateTime.Now;
using (StreamWriter file = new StreamWriter(@"ArknightGrandRollTracker.csv", true))
{
file.WriteLine(dateTime.ToString("dd/MMMM/ yyyy") + "," + _amtOf6Stars + "," + _amtOf5Stars + "," + _amtOf4Stars + "," + _amtOf3Stars);
file.Close();
}
}
catch (Exception ex)
{
throw new ApplicationException("Failed to Save File.", ex);
}
_amtOf6Stars = 0;
_amtOf5Stars = 0;
_amtOf4Stars = 0;
_amtOf3Stars = 0;
SaveCurrentFunction();
}
#endregion Commands
}
}
|
a768382082f37b317e2afdc066bbc480db08a215 | C# | shendongnian/download4 | /first_version_download2/412643-36239287-114178911-2.cs | 2.640625 | 3 | DataTable t; // assume this is table with "Category","Wee","Resolution" columns
var pivotData = new PivotData(
new string[] {"Category","Week"},
new SumAggregatorFactory("Resolution"),
new DataTableReader(t) );
var pivotTable = new PivotTable(
new []{"Week"}, // row dimension(s)
new []{"Category"}, // column dimension(s)
pivotData );
// use pivotTable to access calculated values:
var rowLabels = pivotTable.RowKeys;
var colLabels = pivotTable.ColumKeys;
var cellValue = pivotTable[0, 0].Value; // w1 x cat1 => 26
|
9917e32d3d5340d2f7d90a09eebd988f950daa5e | C# | Argg1025/PostCodeJsonTest | /PostCodeJsonTest/Tests/UnitTest1.cs | 2.546875 | 3 | using System;
using NUnit.Framework;
namespace PostCodeJsonTest
{
[TestFixture]
public class UnitTest1
{
PostcodeService postcodeService = new PostcodeService();
[Test]
public void CheckStatus()
{
Assert.AreEqual(200, postcodeService.postCodeDTO.PostCode.status);
}
[Test]
public void CheckPostCode()
{
Assert.AreEqual(typeof(string), postcodeService.postCodeDTO.Results.postcode.GetType());
Assert.AreEqual(true, postcodeService.PostCodeFormat(postcodeService.postCodeDTO.Results.postcode));
}
[Test]
public void CheckQuality()
{
Assert.AreEqual(typeof(int), postcodeService.postCodeDTO.Results.quality.GetType());
Assert.AreEqual(true, postcodeService.QualityBetween1And9(postcodeService.postCodeDTO.Results.quality));
}
[Test]
public void CheckEastings()
{
Assert.AreEqual(true, postcodeService.StringOrInt(postcodeService.postCodeDTO.Results.eastings));
}
[Test]
public void CheckNorthings()
{
Assert.AreEqual(true, postcodeService.StringOrInt(postcodeService.postCodeDTO.Results.northings));
}
[Test]
public void CheckCountry()
{
Assert.AreEqual(typeof(string), postcodeService.postCodeDTO.Results.country.GetType());
Assert.AreEqual(true,postcodeService.CountryChecker(postcodeService.postCodeDTO.Results.country));
}
[Test]
public void CheckNhs()
{
Assert.AreEqual(true, postcodeService.StringOrNull(postcodeService.postCodeDTO.Results.nhs_ha));
Assert.AreEqual("London", postcodeService.postCodeDTO.Results.nhs_ha);
}
[Test]
public void CheckCounty()
{
Assert.AreEqual(true, postcodeService.StringOrNull(postcodeService.postCodeDTO.Results.admin_county));
}
[Test]
public void CheckLongitude()
{
Assert.AreEqual(true, postcodeService.CheckDecimalPlaces(postcodeService.postCodeDTO.Results.longitude));
}
[Test]
public void CheckLatitude()
{
Assert.AreEqual(true, postcodeService.CheckDecimalPlaces(postcodeService.postCodeDTO.Results.latitude));
}
}
}
|
7c0694d452e9107a10be2805b9254154df160e65 | C# | dis-kz/progeliers | /Synectix/Model/SynectixConnection.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public class SynectixConnection
{
//string _serverName = @".\SQLEXPRESS"; /*@"SERVER\SQLSYNECTIX";*/
//string _modelName = "DataModel";
//string _database = "synectix";
//string _userName = "confdis1";
//string _password = "conf0171017Dis";
//string _connectionString = "";
string _serverName = @"localhost"; /*@"SERVER\SQLSYNECTIX";*/
string _modelName = "DataModel";
string _database = "synectix";
string _userName = "sa";
string _password = "Pass123";
string _connectionString = "";
private static SynectixConnection _instance;
//свойство "экземпляр"
public static SynectixConnection Instance
{
get
{
if (_instance == null)
_instance = new SynectixConnection();
return _instance;
}
}
public string GetConnectionString(int mode)
{
string metadata = String.Format("metadata=res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", _modelName);
string authorization = String.Format("Data Source={0};Initial Catalog={1};persist security info=False;User ID={2};Password={3};" +
"MultipleActiveResultSets=True;App=EntityFramework",_serverName,_database,_userName,_password);
string provider = "provider=System.Data.SqlClient;";
switch (mode)
{
case 1: //подключение модели данных
_connectionString = String.Format(@"{0};{1};provider connection string='{2}';", metadata, provider, authorization);
break;
case 2: //подключение набора данных
_connectionString = String.Format(@"{0}", authorization);
break;
default:
break;
}
return _connectionString;
}
}
}
|
9006c602b53112fd369815b44335e6f7b81385a9 | C# | MangyctSoft/TenzoTest | /Server/Services/OperationService.cs | 2.8125 | 3 | using Common.Interfaces.Services;
using System;
using System.ServiceModel;
namespace Server.Services
{
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.Single)]
public class OperationService : IOperationService
{
public void Start(string userName)
{
Console.WriteLine($"Пользователь {userName} начал запись.");
}
public void Stop(string userName)
{
Console.WriteLine($"Пользователь {userName} завершил запись.");
}
}
}
|
0a948fdb23f7527e816a3217d898b0c7b5f51a38 | C# | WGPQ/CompilerWCL | /CompilerWCL/herramientas/Login_Resources/ManagerUser.cs | 2.71875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CompilerWCL.Login_Resources
{
class ManagerUser
{
string archivo = "user.txt";
private enviaremail env = new enviaremail();
public string user_to_txt(persona u)
{
string cadena = u.nombre+","+u.apellido+","+u.genero+","+u.usuario+","+u.correo+","+u.pass+","+u.confpass;
return cadena;
}
public bool verificacio()
{
return false;
}
public void GuardarUser(List<persona> u)
{
string dato = "";
try
{
foreach (persona us in u)
{
dato=CargarData() + user_to_txt(us);
File.WriteAllText(archivo, dato);
}
}
catch (IOException ex)
{
// MessageBox.Show("Error: " + ex.Message);
}
}
public ManagerUser()
{
if (!File.Exists(archivo))
{
StreamWriter writer = File.CreateText(archivo);
writer.Close();
}
//ObtenerUser();
}
public string CargarData()
{
string content = "";
try
{
var fs = File.OpenRead(archivo);
var stream = new StreamReader(fs);
//string file=fs.Name;
String line;
while ((line = stream.ReadLine()) != null)
{
content += line + "\n";
}
fs.Close();
}
catch (FileNotFoundException ex)
{
//MessageBox.Show("Error: " + ex.Message);
}
return content;
}
public persona ObtenerUser(string user)
{
List<string> lista = new List<string>();
string content = "";
string line;
persona p=null;
try
{
var fs = File.OpenRead(archivo);
var stream = new StreamReader(fs);
//string file=fs.Name;
while ((line = stream.ReadLine()) != null)
{
lista.Add(line);
}
fs.Close();
}
catch (FileNotFoundException ex)
{
//MessageBox.Show("Error: " + ex.Message);
}
string persona=buscar(lista, user);
if (persona!="")
{
p= txt_to_persona(persona);
}
return p;
}
public string buscar(List<string> users,string usuario)
{
string u="";
foreach (string user in users)
{
string[] us = user.Split(',');
if (us[3]==usuario)
{
u = user;
}
}
return u;
}
public persona txt_to_persona(string usuario)
{
string []user = usuario.Split(',');
string nombre = user[0];
string apellido = user[1];
char genero = char.Parse(user[2]);
string us = user[3];
string correo = user[4];
string pass = user[5];
string confpas = user[6];
persona p = new persona(nombre,apellido,genero, us, correo, pass,confpas);
return p;
}
public Object[] VerificarUsuario(string user, string password)
{
string pwd = "";
string email = "";
int numping = 0;
if (ObtenerUser(user) != null)
{
persona p = ObtenerUser(user);
pwd = p.pass;
email = p.correo;
if (pwd == password)
{
numping = enviarMensaje(email);
if (numping > 0)
{
return new Object[] { numping, email };
}
else // -2 error de mensaje no enviado
{
return new Object[] { numping, "Email no enviado" };
}
/*this.Hide();
Form2 f2 = new Form2(p.usuario);
f2.Show();*/
}
else
{
return new Object[] { -1, "Password incorrecto" }; // error de password incorrecto
}
}
else
{
return new Object[] { -3, "Usuario no encontrado" }; // error -3: usuario no encontrado
}
}
/**
* Esta funcion se encarga de enviar al correo el ping aleatorio
* -2 email no se pudo enviar
*
* @param email: correo del ususario al consultar en la bd
* @return : retorno en num aleatroio o el error -2
*/
public int enviarMensaje(string email)
{
string asunto = "Envio de ping para inicio de sesión";
int num = numRandomico();
string mensaje = "ping: " + num;
try
{
env.enviarEmail(email, asunto, mensaje);
return num;
}
catch (Exception ex)
{
return -2; // error -2: mensaje no enviado
}
}
/**
* Genero el numero aleatorio
*/
public int numRandomico()
{
Random rnd = new Random();
return rnd.Next(10000, 90000);
}
public bool Usuariorepetido(string user)
{
if (ObtenerUser(user)!=null)
{
return false;
}
return true;
}
}
}
|
4502dad7ab32c85ce195d7c995cdad033e8610a4 | C# | incarnum/WoTW | /WoTWGame/Assets/DescriptionTextScript.cs | 2.703125 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DescriptionTextScript : MonoBehaviour {
public List<string> descriptions;
public float rowLimit;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void UpdateDescription(int whichDescription) {
//this is the script that displays the ingredient tooltip
//this script holds several strings
//pylonscript tells this script which string to display
//the string gets split up and reassembled with linebreaks, with the float rowLimit, describing how wide each row can be
string garfield = descriptions [whichDescription];
GetComponent<TextMesh> ().text = "";
string builder = "";
string[] parts = garfield.Split (' ');
for (int i = 0; i < parts.Length; i++)
{
GetComponent<TextMesh> ().text += parts[i] + " ";
if (GetComponent<TextMesh>().GetComponent<Renderer>().bounds.extents.x > rowLimit) {
GetComponent<TextMesh> ().text = builder + System.Environment.NewLine + parts[i] + " ";
}
builder = GetComponent<TextMesh> ().text;
}
}
}
|
2e1288a44a9be62e1170119dc8021c67c858d1f4 | C# | alifshits/LeetCode | /Bytes/Reverse Bits.cs | 3.171875 | 3 | public class Solution
{
public uint reverseBits(uint n)
{
uint reversed = 0;
for (var i = 0; i < 32; ++i)
{
if (i > 0) reversed <<= 1;
var last = n & 1;
n >>= 1;
reversed |= last;
}
return reversed;
}
} |
31504408fdf8f6b0a72006bb27acd3e1d78d4425 | C# | cuiopen/httpjsonrpcnet | /src/HttpJsonRpc/JsonRpcResponse.cs | 2.640625 | 3 | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace HttpJsonRpc
{
public class JsonRpcResponse
{
[JsonProperty("jsonrpc")]
public string JsonRpc { get; set; }
[JsonProperty("id")]
public object Id { get; set; }
[JsonProperty("result")]
public object Result { get; set; }
[JsonProperty("error")]
public JsonRpcError JsonRpcError { get; set; }
public static JsonRpcResponse FromResult(object id, object result)
{
var response = Create(id);
response.Result = result;
return response;
}
public static JsonRpcResponse FromError(int code, object id = null, Exception e = null)
{
return FromError(code, id, e?.ToString());
}
public static JsonRpcResponse FromError(int code, object id = null, object data = null)
{
var response = Create(id);
response.JsonRpcError = new JsonRpcError
{
Code = code,
Message = JsonRpcErrorCodes.GetMessage(code),
Data = data == null ? null : JToken.FromObject(data)
};
return response;
}
private static JsonRpcResponse Create(object id)
{
return new JsonRpcResponse
{
JsonRpc = "2.0",
Id = id
};
}
}
} |
8fd2abf3fa84633b21e3272d3b505f5f71da4b29 | C# | revcozmo/absoluterisk | /Risk1/Bolge.cs | 2.90625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace Risk1
{
public class Bolge
{
public Bolge(List<Nokta> nok,String ad)
{
this.noktalar = nok;
this.isim = ad;
}
public Bolge(){}
public List<Nokta> noktalar = new List<Nokta>();
/// <summary>
/// Bölgenin ismini döndürür.
/// </summary>
public String isim="";
/// <summary>
/// Komşu bölgelerin listesini tutar.
/// </summary>
public List<Bolge> komsular = new List<Bolge>();
/// <summary>
/// Bölgenin sahipli olup olmadığını belirtir.
/// </summary>
public bool sahipli = false;
/// <summary>
/// Bölgenin sahibi olan oyuncuyu döndürür.
/// </summary>
public Player sahip;
/// <summary>
/// Asker sayısına Erişmek için kullanılır.
/// </summary>
public Ordu ordu=new Ordu();
/// <summary>
/// Bölgenin numarasını belirtir
/// </summary>
public int number;
/// <summary>
/// Bölgenin listedeki yerini belirtir.
/// </summary>
public int index;
public Color getColor()
{
if (noktalar.Count > 0)
return noktalar[0].renk;
else
return Color.SaddleBrown;
}
}
}
|
5ef7a34b818de7f6d6afd6ee27d423782cb03207 | C# | ctcb57/lemonade_Stand | /lemonade_Stand/lemonade_Stand/Store.cs | 3.15625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lemonade_Stand
{
public class Store
{
//member variables
public int lemonPrice;
public int icePrice;
public int cupPrice;
public int sugarPrice;
//constructor
public Store()
{
lemonPrice = 3;
icePrice = 1;
cupPrice = 1;
sugarPrice = 2;
}
//member methods
public int SellLemons(Player player, Inventory inventory)
{
UserInterface.PurchaseLemonsPrompt();
int response;
while (!int.TryParse(Console.ReadLine(), out response) || player.CashOnHand < (lemonPrice * response))
{
UserInterface.InvalidLemonResponse();
}
player.CashOnHand -= (lemonPrice * response);
inventory.LemonCount += (1 * response);
int moneySpentOnLemons = lemonPrice * response;
return moneySpentOnLemons;
}
public int SellIce(Player player, Inventory inventory)
{
UserInterface.PurchaseIcePrompt();
int response;
while (!int.TryParse(Console.ReadLine(), out response) || player.CashOnHand < (icePrice * response))
{
UserInterface.InvalidIceResponse();
}
player.CashOnHand -= (icePrice * response);
inventory.IceCount += (1 * response);
int moneySpentOnIce = icePrice * response;
return moneySpentOnIce;
}
public int SellSugar(Player player, Inventory inventory)
{
UserInterface.PurchaseSugarPrompt();
int response;
while (!int.TryParse(Console.ReadLine(), out response) || player.CashOnHand < (sugarPrice * response))
{
UserInterface.InvalidSugarResponse();
}
player.CashOnHand -= (sugarPrice * response);
inventory.SugarCount += (1 * response);
int moneySpentOnSugar = sugarPrice * response;
return moneySpentOnSugar;
}
public int SellCups(Player player, Inventory inventory)
{
UserInterface.PurchaseCupsPrompt();
int response;
while (!int.TryParse(Console.ReadLine(), out response) || player.CashOnHand < (cupPrice * response))
{
UserInterface.InvalidCupsResponse();
}
player.CashOnHand -= (cupPrice * response);
inventory.CupCount += (1 * response);
int moneySpentOnCups = cupPrice * response;
return moneySpentOnCups;
}
public int PurchaseItems(Player player, Inventory inventory, Day day)
{
UserInterface.DisplayCashOnHand(player);
int moneySpentOnLemons = SellLemons(player, inventory);
UserInterface.DisplayCashOnHand(player);
int moneySpentOnIce = SellIce(player, inventory);
UserInterface.DisplayCashOnHand(player);
int moneySpentOnSugar = SellSugar(player, inventory);
UserInterface.DisplayCashOnHand(player);
int moneySpentOnCups = SellCups(player, inventory);
UserInterface.DisplayCashOnHand(player);
day.totalPurchase = moneySpentOnCups + moneySpentOnIce + moneySpentOnLemons + moneySpentOnSugar;
return day.totalPurchase;
}
}
}
|
eca1f7d2cf8d5b2592e91484ac1be3fd69163d80 | C# | 21959293/CITS5551_Project | /Assets/Scripts/EndManager.cs | 2.59375 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
/// <summary>
/// Manages the end of the game (doesn't seem to do much though)
/// </summary>
public class EndManager : MonoBehaviour
{
public Text moneyText;
void Start ()
{
//Get final money earnt and display
float money = PlayerPrefs.GetFloat("finalMoney");
moneyText.text = money.ToString("c2");
}
}
|
64b418e411a8c8ad064b39773c7873329de245ba | C# | mnjstwins/Bitcsharp | /bitcsharp/src/lsc.llvm/Instruction/Label.cs | 2.546875 | 3 |
namespace LLVMSharp.Compiler.CodeGenerators.LLVM
{
/// <summary>
/// <label>:
/// </summary>
public class Label : Instruction
{
public string Name;
public Label(Module module)
: base(module)
{
}
public override string EmitCode()
{
return string.Format("{0}:", Name);
}
}
}
|
3a3502a479b0d019b237ac3efc4418dc026bcff1 | C# | bobonic/SproutExam | /Sprout.Exam.WebApp/Controllers/EmployeesController.cs | 2.578125 | 3 | using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Sprout.Exam.Business.DataTransferObjects;
using Sprout.Exam.Common.Enums;
using Sprout.Exam.Repositories;
using Sprout.Exam.Business.Factories;
using CommonEnum = Sprout.Exam.Common.Enums;
using Sprout.Exam.WebApp.Models;
namespace Sprout.Exam.WebApp.Controllers
{
public class EmployeesController : BaseController<IEmployeeRepository>
{
public EmployeesController(IEmployeeRepository employeeRepository) : base(employeeRepository)
{
}
/// <summary>
/// Refactor this method to go through proper layers and fetch from the DB.
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Get()
{
var result = await _repository.GetAll();
return Ok(result);
}
/// <summary>
/// Refactor this method to go through proper layers and fetch from the DB.
/// </summary>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var result = await _repository.GetById(id);
result.Birthdate = DateTime.Parse(result.Birthdate).ToString("yyyy-MM-dd");
return Ok(result);
}
/// <summary>
/// Refactor this method to go through proper layers and update changes to the DB.
/// </summary>
/// <returns></returns>
[HttpPut("{id}")]
public async Task<IActionResult> Put(EmployeeDto input)
{
var result = await _repository.Update(input.Id, input);
if (result)
{
return Ok(result);
}
return BadRequest(false);
}
/// <summary>
/// Refactor this method to go through proper layers and insert employees to the DB.
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Post(EmployeeDto input)
{
var result = await _repository.Create(input);
if (result)
{
return Ok(result);
}
return BadRequest(false);
}
/// <summary>
/// Refactor this method to go through proper layers and perform soft deletion of an employee to the DB.
/// </summary>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
var result = await _repository.Delete(id);
if (result)
{
return Ok(result);
}
return BadRequest(false);
}
/// <summary>
/// Refactor this method to go through proper layers and use Factory pattern
/// </summary>
/// <param name="id"></param>
/// <param name="absentDays"></param>
/// <param name="workedDays"></param>
/// <returns></returns>
[HttpPost("{id}/calculate")]
public async Task<IActionResult> Calculate(CalculateRequestModel request)
{
EmployeeTypeFactory factory = null;
var result = await _repository.GetById(request.Id);
if (result == null) return NotFound();
var type = (CommonEnum.EmployeeType)result.TypeId;
switch (type)
{
case CommonEnum.EmployeeType.Regular:
factory = new RegularEmployeeFactory((decimal)EmployeeTypeRates.Regular, request.Days, 12);
break;
case CommonEnum.EmployeeType.Contractual:
factory = new ContractualEmployeeFactory((decimal)EmployeeTypeRates.Contractual, request.Days);
break;
}
var item = factory.Calculate();
return Ok(item.Salary);
}
}
}
|
c514d1de686e09be8d3a9b90056fea46e407e064 | C# | SkieeL/Laboratorio-II | /PARCIALES/Práctica 1 SP Lab II/Entidades/Goma.cs | 3.015625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Goma : Utiles
{
private bool _soloLapiz;
public override double Precio {
get { return base._precio; }
set { base._precio = value; }
}
public override string Marca {
get { return base._marca; }
set { base._marca = value; }
}
public Goma(double precio, string marca, bool soloLapiz) : base(precio, marca) {
this._soloLapiz = soloLapiz;
}
protected override string utilesToString() {
StringBuilder retorno = new StringBuilder();
retorno.Append(base.utilesToString());
retorno.AppendFormat(" -- Borra lapiz: {0}", this._soloLapiz == true ? "Si" : "No");
return retorno.ToString();
}
public override string ToString() {
return this.utilesToString();
}
}
}
|
d08accd97e804133e70fda0edb63a4f719326d87 | C# | rwg0/ConeSharp | /ConeSharp/RADecl.cs | 2.703125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConeSharp
{
class RADecl
{
public double RA { get; set; }
public double RADegrees { get { return RA/24*360; } }
public double Declination { get; set; }
static public RADecl operator -(RADecl left, RADecl right)
{
return new RADecl() {RA = left.RA - right.RA, Declination = left.Declination - right.Declination};
}
}
}
|
1d35f8292af6fb5aac86df63f11788e9f2388f01 | C# | mndspc/Chapter5-Repo | /ArrayAndCollections/ArrayAndCollections/HashTableAndSortedListDemo.cs | 3.640625 | 4 | using System;
using System.Collections;
namespace ArrayAndCollections
{
// This program demo. how to use HashTable and SortedList non-generic collection
class HashTableAndSortedListDemo
{
static void Main()
{
// HashTable and SortedList maintain data in pairs (key and value)
Hashtable gstStateCodes = new Hashtable();
gstStateCodes.Add("MH",27);
gstStateCodes.Add("GJ",24);
gstStateCodes.Add("KA",29);
gstStateCodes.Add("TL",36);
gstStateCodes.Add("AP",28);
gstStateCodes.Add("DL",7);
Console.WriteLine("Count is:{0}",gstStateCodes.Count);
Console.WriteLine("GST Code of AP:{0}", gstStateCodes["AP"]);
gstStateCodes["AP"] = 29;
Console.WriteLine("GST Code of AP:{0} after modifying", gstStateCodes["AP"]);
foreach(var key in gstStateCodes.Keys)
{
Console.WriteLine("Key={0} and Value={1}",key,gstStateCodes[key]);
}
gstStateCodes.Remove("DL");
Console.WriteLine("After Removing DL");
foreach (var key in gstStateCodes.Keys)
{
Console.WriteLine("Key={0} and Value={1}", key, gstStateCodes[key]);
}
Console.WriteLine("Sorted List data");
SortedList sortedList = new SortedList();
sortedList.Add("xyz",23);
sortedList.Add("abc",2);
sortedList.Add( "hello",22);
foreach (var key in sortedList.Keys)
{
Console.WriteLine("Key={0} and Value={1}", key, sortedList[key]);
}
Console.ReadLine();
}
}
}
|
2500fb4ed396bfebe6037765a47ca1e6ac57fb0c | C# | nathalyoliveira/LP3_IFSP | /Aula13/Aula13/Aula13/Program.cs | 3.296875 | 3 | using System;
namespace Aula13
{
class Program
{
static void mostrarArea(IForma forma)
{
Console.WriteLine("Área da forma: " + forma.calcularArea());
}
static void Main(string[] args)
{
IForma f1 = new Quadrado(10.0);
mostrarArea(f1);
IForma f2 = new Retangulo(6.5, 7.0);
mostrarArea(f2);
IForma f3 = new Circulo(7.0);
mostrarArea(f3);
IForma f4 = new Triangulo(7.0, 2.5);
mostrarArea(f4);
}
}
}
|
f90ee4eda5bd8a8768dec86758e741fd871ec6bb | C# | danruimdegame/MAIN-2D | /Assets/SCRIPT/LEVEL 1/SPECIAL PLATFORMS/MovingPlatformControl.cs | 2.59375 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatformControl : MonoBehaviour {
public GameObject platform;
public Transform currentPoint;
public Transform[] positions;
public int pointSelection = 0;
public float moveSpeed = 2f;
public float waitTime = 0.5f;
void Start () {
currentPoint = positions[pointSelection];
StartCoroutine(Move());
}
IEnumerator Move(){
while(true){
platform.transform.position = Vector3.MoveTowards(platform.transform.position, currentPoint.position, Time.deltaTime*moveSpeed);
if (platform.transform.position == currentPoint.position){
pointSelection++;
yield return new WaitForSeconds(waitTime);
}
if(pointSelection == positions.Length){
pointSelection = 0;
yield return new WaitForSeconds(waitTime);
}
currentPoint = positions[pointSelection];
yield return null;
}
}
void Update () {
}
}
|
96c0ce063eb8952a3a9717d1be2c063f10fe1fbe | C# | notusedusername/doctorCSharp | /ShopServer/Model/Items/SerializedUser.cs | 2.78125 | 3 |
using DoctorCSharpServer.Controllers.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DoctorCSharpServer.Model.Items
{
public class SerializedUser
{
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public SerializedUser()
{
}
public void validate()
{
validateName();
validateEmail();
validatePassword();
}
private void validateName()
{
if(string.IsNullOrWhiteSpace(name)){
throw new InvalidInputException("The value of " + nameof(name) + " can not be empty!");
}
}
private void validateEmail()
{
if (string.IsNullOrWhiteSpace(email))
{
throw new InvalidInputException("The value of " + nameof(email) + " can not be empty!");
}
}
private void validatePassword()
{
if (string.IsNullOrWhiteSpace(password))
{
throw new InvalidInputException("The value of " + nameof(password) + " can not be empty!");
}
}
}
}
|
6bea857b58bd69c62db02e8ffd13029f067fa951 | C# | sunnytyra/ProductSite | /ProductSite/Data/ProductBase.cs | 2.609375 | 3 | using ProductSite.Interfaces.Enum;
using ProductSite.Interfaces.Public;
using System;
using System.Collections.Generic;
using System.Text;
namespace ProductSite.Data
{
class ProductBase : IProduct
{ //TODO remove this may not be needed
private readonly IProduct product;
public ProductTypeEnum ProductType => product.ProductType;
public ProductEnum Product => product.Product;
public ProductGenreEnum ProductGenre => product.ProductGenre;
public ProductCost Cost { get; set; }
public ProductBase(IProduct product)
{
this.product = product;
}
public bool Sold()
{
return product.Sold();
}
}
}
|
8eb8708342ab05b0e6487a16b2952fe1dc11210d | C# | Hemant-Jain-Author/Problem-Solving-in-Data-Structures-Algorithms-using-CSharp | /HashTable/HashTableExercise.cs | 3.671875 | 4 | using System;
using System.Collections.Generic;
public class HashTableExercise
{
public static bool IsAnagram(char[] str1, char[] str2)
{
int size1 = str1.Length;
int size2 = str2.Length;
if (size1 != size2)
{
return false;
}
Dictionary<char, int> hm = new Dictionary<char, int>();
foreach (char ch in str1)
{
if (hm.ContainsKey(ch))
{
hm[ch] = hm[ch] + 1;
}
else
{
hm[ch] = 1;
}
}
foreach (char ch in str2)
{
if (hm.ContainsKey(ch) == false || hm[ch] == 0)
{
return false;
}
else
{
hm[ch] = hm[ch] - 1;
}
}
return true;
}
// Testing code.
public static void Main1()
{
char[] first = "hello".ToCharArray();
char[] second = "elloh".ToCharArray();
char[] third = "world".ToCharArray();
Console.WriteLine("IsAnagram : " + IsAnagram(first, second));
Console.WriteLine("IsAnagram : " + IsAnagram(first, third));
}
/*
IsAnagram : True
IsAnagram : False
*/
public static string RemoveDuplicate(char[] str)
{
HashSet<char> hs = new HashSet<char>();
string output = "";
foreach (char ch in str)
{
if (hs.Contains(ch) == false)
{
output += ch;
hs.Add(ch);
}
}
return output;
}
// Testing code.
public static void Main2()
{
char[] first = "hello".ToCharArray();
Console.WriteLine(RemoveDuplicate(first));
}
/*
helo
*/
public static int FindMissing(int[] arr, int start, int end)
{
HashSet<int> hs = new HashSet<int>();
foreach (int i in arr)
{
hs.Add(i);
}
for (int curr = start; curr <= end; curr++)
{
if (hs.Contains(curr) == false)
{
return curr;
}
}
return int.MaxValue;
}
// Testing code.
public static void Main3()
{
int[] arr = new int[] { 1, 2, 3, 5, 6, 7, 8, 9, 10 };
Console.WriteLine(FindMissing(arr, 1, 10));
}
/*
4
*/
public static void PrintRepeating(int[] arr)
{
HashSet<int> hs = new HashSet<int>();
Console.Write("Repeating elements are : ");
foreach (int val in arr)
{
if (hs.Contains(val))
{
Console.Write(val + " ");
}
else
{
hs.Add(val);
}
}
}
// Testing code.
public static void Main4()
{
int[] arr1 = new int[] { 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1 };
PrintRepeating(arr1);
}
/*
Repeating elements are : 4 1
*/
public static void PrintFirstRepeating(int[] arr)
{
int i;
int size = arr.Length;
HashSet<int> hs = new HashSet<int>();
int firstRepeating = int.MaxValue;
for (i = size - 1; i >= 0; i--)
{
if (hs.Contains(arr[i]))
{
firstRepeating = arr[i];
}
hs.Add(arr[i]);
}
Console.WriteLine("First Repeating number is : " + firstRepeating);
}
// Testing code.
public static void Main5()
{
int[] arr1 = new int[] { 1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 1 };
PrintFirstRepeating(arr1);
}
/*
First Repeating number is : 1
*/
public static int HornerHash(char[] key, int tableSize)
{
int size = key.Length;
int h = 0;
int i;
for (i = 0; i < size; i++)
{
h = (32 * h + key[i]) % tableSize;
}
return h;
}
public static void Main(string[] args)
{
Main1();
Main2();
Main3();
Main4();
Main5();
}
} |
56bcd5b2dd104091a63012473372326a1afdde4b | C# | keisukenakamura0711/WPFApp_Test3 | /Views/Behaviors/CommonDialogBehavior.cs | 2.828125 | 3 | using Microsoft.Win32;
using System;
using System.Windows;
namespace WPFApp_Test3.Views.Behaviors
{
/// <summary>
/// コモンダイアログに関するビヘイビアを表します。
/// </summary>
internal class CommonDialogBehavior
{
#region Callback 添付プロパティ
/// <summary>
/// Action<bool, string> 型のCallback添付プロパティを定義します。
/// </summary>
public static readonly DependencyProperty CallbackProperty = DependencyProperty.RegisterAttached("Callback",
typeof(Action<bool, string>),
typeof(CommonDialogBehavior),
new PropertyMetadata(null, OnCallbackPropertyChanged));
/// <summary>
/// Callback添付プロパティを取得します。
/// </summary>
/// <Param name="target">対象とするDependencyObjectを指定します</param>
/// <returns>取得した値を返します</returns>
public static Action<bool, string> GetCallback(DependencyObject target)
{
return (Action<bool, string>)target.GetValue(CallbackProperty);
}
/// <summary>
/// Callback添付プロパティを設定します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <param name="value">設定する値を指定します。</param>
public static void SetCallback(DependencyObject target, Action<bool, string> value)
{
target.SetValue(CallbackProperty, value);
}
/// <summary>
/// string 型の Title 添付プロパティを定義します。
/// </summary>
public static readonly DependencyProperty TitleProperty = DependencyProperty.RegisterAttached("Title",
typeof(string),
typeof(CommonDialogBehavior),
new PropertyMetadata("ファイルを開く"));
/// <summary>
/// Title添付プロパティを取得します。
/// </summary>
/// <Param name="target">対象とするDependencyObjectを指定します</param>
/// <returns>取得した値を返します</returns>
public static string GetTitle(DependencyObject target)
{
return (string)target.GetValue(TitleProperty);
}
/// <summary>
/// Title添付プロパティを設定します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <param name="value">設定する値を指定します。</param>
public static void SetTitle(DependencyObject target, string value)
{
target.SetValue(TitleProperty, value);
}
/// <summary>
/// string 型の Filter 添付プロパティを定義します。
/// </summary>
public static readonly DependencyProperty FilterProperty = DependencyProperty.RegisterAttached("Filter",
typeof(string),
typeof(CommonDialogBehavior),
new PropertyMetadata("すべてのファイル(*.*) | *.* "));
/// <summary>
/// Filter添付プロパティを取得します。
/// </summary>
/// <Param name="target">対象とするDependencyObjectを指定します</param>
/// <returns>取得した値を返します</returns>
public static string GetFilter(DependencyObject target)
{
return (string)target.GetValue(FilterProperty);
}
/// <summary>
/// Filter添付プロパティを設定します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <param name="value">設定する値を指定します。</param>
public static void SetFilter(DependencyObject target, string value)
{
target.SetValue(FilterProperty, value);
}
/// <summary>
/// string 型の Multiselect 添付プロパティを定義します。
/// </summary>
public static readonly DependencyProperty MultiselectProperty = DependencyProperty.RegisterAttached("Multiselect",
typeof(bool),
typeof(CommonDialogBehavior),
new PropertyMetadata(false));
/// <summary>
/// Multiselect添付プロパティを取得します。
/// </summary>
/// <Param name="target">対象とするDependencyObjectを指定します</param>
/// <returns>取得した値を返します</returns>
public static bool GetMultiselect(DependencyObject target)
{
return (bool)target.GetValue(MultiselectProperty);
}
/// <summary>
/// Filter添付プロパティを設定します。
/// </summary>
/// <param name="target">対象とする DependencyObject を指定します。</param>
/// <param name="value">設定する値を指定します。</param>
public static void SetMultiselect(DependencyObject target, bool value)
{
target.SetValue(MultiselectProperty, value);
}
/// <summary>
/// Callback添付プロパティ変更イベントハンドラ
/// </summary>
/// <param name="sender">イベント発行元</param>
/// <param name="e">イベント引数</param>
private static void OnCallbackPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var callback = GetCallback(sender);
if(callback != null)
{
var dlg = new OpenFileDialog()
{
Title = GetTitle(sender),
Filter = GetFilter(sender),
Multiselect = GetMultiselect(sender),
};
var owner = Window.GetWindow(sender);
var result = dlg.ShowDialog(owner);
callback(result.Value, dlg.FileName);
}
}
#endregion Callback 添付プロパティ
}
}
|
a0be412d9e91f567da83f33a6f4a83acdca0fe03 | C# | devatwork/Premotion-Mansion | /src/Premotion.Mansion.Core/IO/EmbeddedResources/EmbeddedResource.cs | 2.859375 | 3 | using System;
using System.IO;
using System.Reflection;
using System.Text;
using Premotion.Mansion.Core.Patterns;
namespace Premotion.Mansion.Core.IO.EmbeddedResources
{
/// <summary>
/// Implements the <see cref="IResource"/> interface for embedded resources.
/// </summary>
public class EmbeddedResource : IResource
{
#region Nested type: EmbeddedResourceInputPipe
/// <summary>
/// Implements the <see cref="IInputPipe"/> for embedded resources.
/// </summary>
private class EmbeddedResourceInputPipe : DisposableBase, IInputPipe
{
#region Constructors
/// <summary>
/// Constructs the <see cref="EmbeddedResourceInputPipe"/>.
/// </summary>
/// <param name="resourceName">The name of the resource which to load.</param>
/// <param name="assemblyName">The <see cref="Assembly"/> from which to load the resource.</param>
public EmbeddedResourceInputPipe(string resourceName, Assembly assemblyName)
{
// validate arguments
if (string.IsNullOrEmpty(resourceName))
throw new ArgumentNullException("resourceName");
if (assemblyName == null)
throw new ArgumentNullException("assemblyName");
// open the resource
var resourceStream = assemblyName.GetManifestResourceStream(resourceName);
if (resourceStream == null)
throw new InvalidOperationException(string.Format("Could not load resource '{0}' from assembly '{1}'", resourceName, assemblyName.FullName));
// open the resource
reader = new StreamReader(resourceStream);
}
#endregion
#region Implementation of IPipe
/// <summary>
/// Gets the encoding of this pipe.
/// </summary>
public Encoding Encoding
{
get { return Encoding.UTF8; }
}
#endregion
#region Implementation of IInputPipe
/// <summary>
/// Gets the reader for this pipe.
/// </summary>
public TextReader Reader
{
get
{
CheckDisposed();
return reader;
}
}
/// <summary>
/// Gets the underlying stream of this pipe. Use with caution.
/// </summary>
public Stream RawStream
{
get
{
CheckDisposed();
return reader.BaseStream;
}
}
#endregion
#region Overrides of DisposableBase
/// <summary>
/// Dispose resources. Override this method in derived classes. Unmanaged resources should always be released
/// when this method is called. Managed resources may only be disposed of if disposeManagedResources is true.
/// </summary>
/// <param name="disposeManagedResources">A value which indicates whether managed resources may be disposed of.</param>
protected override void DisposeResources(bool disposeManagedResources)
{
if (!disposeManagedResources)
return;
reader.Dispose();
}
#endregion
#region Private Fields
private readonly StreamReader reader;
#endregion
}
#endregion
#region Constructors
/// <summary>
/// Constructs this embedded resource.
/// </summary>
/// <param name="name">The name of the resource.</param>
/// <param name="assemblyName">The <see cref="Assembly"/> from which to load the resource.</param>
/// <param name="path">The <see cref="IResourcePath"/>.</param>
/// <exception cref="ArgumentNullException">Thrown if either <paramref name="name"/>, <paramref name="assemblyName"/> or <paramref name="path"/> is null.</exception>
public EmbeddedResource(string name, AssemblyName assemblyName, IResourcePath path)
{
// validate arguments
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (assemblyName == null)
throw new ArgumentNullException("assemblyName");
if (path == null)
throw new ArgumentNullException("path");
// set values
resourceName = assemblyName.Name + "." + name;
this.assemblyName = assemblyName;
Path = path;
}
#endregion
#region Implementation of IResource
/// <summary>
/// Opens this resource for reading.
/// </summary>
/// <returns>Returns a <see cref="IOutputPipe"/>.</returns>
public IInputPipe OpenForReading()
{
return new EmbeddedResourceInputPipe(resourceName, Assembly.Load(assemblyName));
}
/// <summary>
/// Opens this resource for writing.
/// </summary>
/// <returns>Returns a <see cref="IInputPipe"/>.</returns>
public IOutputPipe OpenForWriting()
{
throw new NotSupportedException("Can not write to embedded resources.");
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>A hash code for the current <see cref="IResource"/>.</returns>
public string GetResourceIdentifier()
{
return resourceName;
}
/// <summary>
/// Gets the path of this resource.
/// </summary>
public IResourcePath Path { get; private set; }
/// <summary>
/// Gets the size of this resource in bytes.
/// </summary>
public long Length
{
get { throw new NotSupportedException("The length is not supported on EmbeddedResources."); }
}
/// <summary>
/// Gets the version of this resource.
/// </summary>
public string Version
{
get { return assemblyName.Version.ToString(); }
}
#endregion
#region Private Fields
private readonly AssemblyName assemblyName;
private readonly string resourceName;
#endregion
}
} |
3ee501016230cf50484c0633e305c2aab6461690 | C# | eweader/SharedMemory-master | /Experiments/PriceConsumerConsole/Program.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PriceConsumerConsole
{
class Program
{
static void Main(string[] args)
{
string mname = "PovEURUSDm5" ;
using (var consumer
= new SharedMemory.SharedArray<int>(mname))
{
;
Console.WriteLine(consumer[0]);
Console.WriteLine(consumer[consumer.Length - 1]);
}
}
}
}
|
ec779eace1cfbd5c548f8ee674b1d236e6ff1e1e | C# | LittleKolio/CSharp | /CSharp Advanced/16_LINQ_Exercises/Exercises_08_Weak_Students.cs | 3.875 | 4 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LINQ_Exercises
{
class Exercises_08_Weak_Students
{
static void Main()
{
/*
List<string[]> students = new List<string[]>();
while (true)
{
string input = Console.ReadLine();
if (input.ToLower() == "end") { break; }
string[] temp = Regex.Split(input, @"(?<!\d)\s");
if (Regex.Matches(temp[2], "[23]").Count >= 2)
{
students.Add(new string[]
{
temp[0],
temp[1]
});
}
}
students.ForEach(stu => Console.WriteLine(string.Join(" ", stu)));
*/
List<string[]> students = new List<string[]>();
while (true)
{
string input = Console.ReadLine();
if (input.ToLower() == "end") { break; }
students.Add(input.Split(' '));
}
students
.Where(str =>
str.Skip(2).Count(num =>
int.Parse(num) <= 3)
>= 2)
.ToList()
.ForEach(stu =>
Console.WriteLine(string.Join(" ", stu.Take(2))));
}
}
}
|
003ebdbae3a596f684188dca133b6f498375f50a | C# | InNomineMortis/internet_technologies_components | /Lab3/Lab3/Figure.cs | 3.625 | 4 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lab3
{
public abstract class Figure : IPrint, IComparable
{
public abstract double Area();
public int CompareTo(object obj)
{
switch (obj)
{
case null:
return 1;
case Figure figure:
return Area().CompareTo(figure.Area());
default:
throw new ArgumentException("Used object is not a figure");
}
}
public void Print()
{
Console.WriteLine(ToString());
}
}
}
|
867ab213f83ab49a9f92838b06ee1495b2423706 | C# | RodrigodeMoura/contravania | /RunAndGun/RunAndGun/StageObjects/Platform.cs | 2.796875 | 3 | using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RunAndGun.GameObjects
{
public class Platform
{
public enum PlatformTypes
{
Normal,
Stairs,
StairsBottom
}
private Rectangle _platformBounds;
private PlatformTypes _platformType;
public Platform(Rectangle platformBounds, PlatformTypes platformType)
{
_platformBounds = platformBounds;
_platformType = platformType;
}
public Rectangle PlatformBounds
{
get { return _platformBounds; }
}
public PlatformTypes PlatformType
{
get
{
return _platformType;
}
}
}
}
|
3894573402ec8fdd2db83e8c58385d3ce9457da0 | C# | LMErika/sisComercial | /SistemaComercial/DAO/daoUsuario.cs | 2.59375 | 3 | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entidad;
namespace DAO
{
public class daoUsuario
{
#region singleton
private static readonly daoUsuario conexUsuario = new daoUsuario();
public static daoUsuario Instancia
{
get { return daoUsuario.conexUsuario; }
}
#endregion singleton
#region metodos
public Boolean IniciarSesion(String user, String pass)
{
bool sesion = false;
SqlCommand cmd = null;
try
{
SqlConnection cn = Conexion.Instancia.Conectar();
cmd = new SqlCommand("IniciarSesion", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);
cn.Open();
int i = cmd.ExecuteNonQuery();
if (i > 0)
{ sesion = true; }
}
catch (Exception e)
{
throw e;
}
return sesion;
}
#endregion metodos
}
}
|
d51d4fea49cedafcc9ba215f49f7a32205703886 | C# | zl1814264-lay/C-Sharp-Samples-for-Beginners | /Collatz Sequence.cs | 3.4375 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication210
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Generation of Collatz Sequence");
Console.WriteLine("\n");
Console.WriteLine("Enter the Number");
int N = Convert.ToInt32(Console.ReadLine());
int n;
n = N;
Console.WriteLine("\n");
Console.WriteLine("\n");
Console.Write("{0} ", N);
if (n % 2 == 0)
{
collatz(N);
}
else
{
collatz1(N);
}
}
private static void Exit(int value)
{
Console.Write("{0} ", value/2);
Console.ReadLine();
}
public static void collatz(int even)
{
int e = 0; e = even / 2;
if (e != 1)
{
Console.Write("{0} ", e);
if (e % 2 == 0)
{
collatz(e);
}
else
{
collatz1(e);
//return e;
}
}
else
{
Exit(even);
}
}
public static void collatz1(int odd)
{
int o=0,b=1,a,dummy=0;
a = (odd * 3) + b;
o = a;
Console.Write("{0} ", o);
if (o % 2 == 0)
{
collatz(o);
//return o;
}
else
{
collatz1(o);
//return o;
}
}
}
}
|
597a3ac2cf62334bc3e0d1ac01609333f43d2aae | C# | rianjs/PassiveIncomeCalculator | /PassiveIncome/Program.cs | 3.0625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PassiveIncome
{
internal class Program
{
static void Main(string[] args)
{
BridgeToAsync().Wait();
Console.ReadLine();
}
private static async Task BridgeToAsync()
{
var downloader = new HistoricalDataDownloader("VFIAX", new DateTime(2007, 01, 01));
var rawContent = await downloader.DownloadHistoricalDataAsync();
var vfiaxHist = new TickerCsvParser(rawContent).Parse();
var queryableHistory = TickerHistory(vfiaxHist);
var startDate = DateTime.UtcNow.AddYears(-1);
var priceOnOrAfterStartDate = queryableHistory.First(pair => pair.Key >= startDate);
Console.WriteLine(priceOnOrAfterStartDate.Key + Environment.NewLine + priceOnOrAfterStartDate.Value.AdjustedClose);
}
internal static Dictionary<DateTime, SymbolDatum> TickerHistory(IEnumerable<SymbolDatum> dataDump)
{
return dataDump.ToDictionary(d => d.Date, d => d);
}
internal static double ComputeNumberOfShares(decimal sharePrice, decimal principal)
=> Math.Round(Convert.ToDouble(principal / sharePrice), 4);
}
}
|
894163bb2fbb8143d00b2246cca34b2b0d2771fd | C# | KishorNaik/Sol_Ref_Local_Returns_C- | /Sol_Demo/Sol_Demo/Program.cs | 3.421875 | 3 | // Ref local and return
using System;
namespace Sol_Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
#region Exmaple One
Example1 example = new Example1();
int[] numbers = new[] { 1, 2, -4, 5, 6 };
int notFoundValue = 0;
// Without Ref
int result = example.GetFirstNegativeNumberWithoutRef(numbers);
Console.WriteLine(result);// -4
result++; //-3
Console.WriteLine(result);// -3
result = example.GetFirstNegativeNumberWithoutRef(numbers);
Console.WriteLine(result);// -4 (without ref return it would chnaged the value)
// With Ref
ref int result1 = ref example.GetFirstNegativeNumberWithRef(numbers, ref notFoundValue);
Console.WriteLine(result);// -4
result1++; //-3
Console.WriteLine(result1);//-3
result1 = ref example.GetFirstNegativeNumberWithRef(numbers, ref notFoundValue);
Console.WriteLine(result1);// -3 (With ref return it would changed the value)
#endregion
#region Example1
Example2 example2 = new Example2();
// Without Ref
int result2 =example2.AddWithoutRef(2, 2);
Console.WriteLine(result2); // 4
Console.WriteLine(example2.result);// 4
result2 = result2 + 1;
Console.WriteLine(result2); // 5
Console.WriteLine(example2.result);// 4 (Without Ref Return it would not changed the value)
result2 = example2.AddWithoutRef(2, 2);
Console.WriteLine(result2); // 4
Console.WriteLine(example2.result);// 4
// With Ref
ref int result3 = ref example2.AddWithRef(2, 2);
Console.WriteLine(result3); // 4
Console.WriteLine(example2.result);// 4
result3 = result2 + 1;
Console.WriteLine(result2); // 5
Console.WriteLine(example2.result);// 5 (with Ref Return it would changed the value)
result3 = ref example2.AddWithRef(2, 2);
Console.WriteLine(result3); // 4
Console.WriteLine(example2.result);// 5
#endregion
}
}
public class Example1
{
public int GetFirstNegativeNumberWithoutRef(int[] numbers)
{
for (var i = 0; i < numbers.Length; i++)
{
if (numbers[i] < 0)
{
return numbers[i];
}
}
return 0;
}
public ref int GetFirstNegativeNumberWithRef(int[] numbers,ref int notFoundValue)
{
for (var i = 0; i < numbers.Length; i++)
{
if (numbers[i] < 0)
{
return ref numbers[i];
}
}
return ref notFoundValue;
}
}
public class Example2
{
public int result = 0;
public int AddWithoutRef(int value1, int value2)
{
result = value1 + value2;
return result;
}
public ref int AddWithRef(int value1,int value2)
{
result = value1 + value2;
return ref result;
}
}
}
|
5d4d8a8e66ef4a5ada0470327a87badf14bbdde6 | C# | nguoiyoujie/Primrose | /src/Primrose.Expressions/Tree/Statements/Statement.cs | 2.90625 | 3 | using System.Text;
namespace Primrose.Expressions.Tree.Statements
{
internal class Statement : CStatement
{
private readonly CStatement _statement;
internal Statement(ContextScope scope, Lexer lexer) : base(scope, lexer)
{
// IFTHENELSE (GetNext)
while (lexer.TokenType == TokenEnum.NOTHING || lexer.TokenType == TokenEnum.COMMENT)
{
lexer.Next();
}
_statement = GetNext(scope, lexer);
}
public override CStatement Get()
{
return _statement.Get();
}
public override bool Evaluate(IContext context, ref Val retval)
{
return _statement.Evaluate(context, ref retval);
}
public override void Write(StringBuilder sb)
{
_statement.Write(sb);
}
}
}
|
86e8869309245a1dec49239788cfa0c7ec9274c2 | C# | kim4t/SEP | /C# 04/Exercise1/Program.cs | 3.453125 | 3 | using System;
namespace Exercise1
{
class Program
{
static void Main(string[] args)
{
Customer c = new Customer(1);
c.Name = "Maria Anders";
c.City = "Berlin";
Console.WriteLine(c);
}
}
public class Customer
{
public int CustomerID { get; private set; }
public string Name { get; set; }
public string City { get; set; }
public Customer(int ID)
{
CustomerID = ID;
}
public override string ToString()
{
return Name + "\t" + City + "\t" + CustomerID;
}
}
}
|
9099fd73d946cf4ef9abea58069ebc513c24adee | C# | zyque-sys/aplicaciones-web | /visual studio repo/FUNPOO2020_2/III_5CodigoDesdeUML/Perro.cs | 2.71875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace III_5CodigoDesdeUML
{
public class Perro : Animal
{
private int cPerro1;
private string cPerro2;
public event System.EventHandler Ladrar;
public int Cperro1
{
get { return this.cPerro1; }
set { this.cPerro1 = value; }
}
public string Cperro2
{
get { return this.cPerro2; }
set { this.cPerro2 = value; }
}
public void Mperro1()
{
}
public void Mperro2()
{
}
}
}
|
0d22797e0eece0c9f82cf2f475dd6badc5f0a049 | C# | ab4d/Ab3d.PowerToys.Wpf.Samples | /Ab3d.PowerToys.Samples/Text3D/LineWithTextSample.xaml.cs | 2.546875 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using Ab3d.Visuals;
namespace Ab3d.PowerToys.Samples.Text3D
{
/// <summary>
/// Interaction logic for LineWithTextSample.xaml
/// </summary>
public partial class LineWithTextSample : Page
{
public LineWithTextSample()
{
InitializeComponent();
UseTextBlockVisual3DInfoControl.InfoText =
@"When checked, then LineWithTextVisual3D is using a TextBlockVisual3D to show 3D text. When unchecked then 3D lines are used to show the text (using an old plotter font).
Using TextBlockVisual3D provides much more text rendering options and allows using any font but may produce some problems because of showing semi-transparent texture (sorting objects by camera distance; or using Ab3d.DXEngine and alpha-clip threshold).";
}
private void OnUseTextBlockVisual3DCheckedChanged(object sender, RoutedEventArgs e)
{
if (!this.IsLoaded)
return;
var useTextBlockVisual3D = UseTextBlockVisual3DCheckBox.IsChecked ?? false;
foreach (var lineWithTextVisual3D in MainViewport.Children.OfType<LineWithTextVisual3D>())
{
lineWithTextVisual3D.UseTextBlockVisual3D = useTextBlockVisual3D;
if (useTextBlockVisual3D)
{
// When UseTextBlockVisual3D is set to true, we can change text rendering options on UsedTextBlockVisual3D property:
// The following properties are already set by the LineWithTextVisual3D:
//Text = this.Text,
//Position = textCenterPosition,
//PositionType = PositionTypes.Center,
//TextDirection = lineDirection,
//UpDirection = this.TextUpDirection,
//Size = new Size(0, this.FontSize), // Set only height; width will be set automatically by the TextBlockVisual3D
//Foreground = new SolidColorBrush(this.LineColor),
lineWithTextVisual3D.UsedTextBlockVisual3D.FontFamily = new FontFamily("Arial");
lineWithTextVisual3D.UsedTextBlockVisual3D.RenderBitmapSize = new Size(256, 64);
}
}
}
}
}
|
c174f7d392d381d6dd531999cbd9d297fff20e3b | C# | PacktPublishing/Programming-in-C-Sharp-Exam-70-483-MCSD-Guide | /Chapter07/ExceptionSamples.cs | 3.015625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Chapter7
{
internal class ExceptionSamples
{
public static void ExceptionTest1()
{
string str = string.Empty;
int parseInt = int.Parse(str);
}
public static void ExceptionTest2()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (FormatException e)
{
Console.WriteLine($"Exception Data: {e.Data}");
Console.WriteLine($"Exception HelpLink: {e.HelpLink}");
Console.WriteLine($"Exception HResult: {e.HResult}");
Console.WriteLine($"Exception InnerException: {e.InnerException}");
Console.WriteLine($"Exception Message: {e.Message}");
Console.WriteLine($"Exception Source: {e.Source}");
Console.WriteLine($"Exception TargetSite: {e.TargetSite}");
Console.WriteLine($"Exception StackTrace: {e.StackTrace}");
}
}
public static void ExceptionTest3()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (ArgumentException ex)
{
Console.WriteLine("Argument Exception caught");
}
catch (FormatException e)
{
Console.WriteLine("Format Exception caught");
}
catch (Exception ex1)
{
Console.WriteLine("Generic Exception caught");
}
}
public static void ExceptionTest4()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
catch (ArgumentException ex)
{
Console.WriteLine("Argument Exception caught");
}
catch (FormatException e)
{
Console.WriteLine("Format Exception caught");
}
catch (Exception ex1)
{
Console.WriteLine("Generic Exception caught");
}
finally
{
Console.WriteLine("Finally block executed");
}
}
public static void ExceptionTest5()
{
string[] strNumbers = new string[] {"One","Two","Three","Four" };
try
{
for (int i = 0; i <= strNumbers.Length; i++)
{
Console.WriteLine(strNumbers[i]);
}
}
catch (System.IndexOutOfRangeException e)
{
Console.WriteLine("Index is out of range.");
throw new System.ArgumentOutOfRangeException(
"Index is out of range.", e);
}
}
public static void ExceptionTest6()
{
System.IO.FileStream file = null;
System.IO.FileInfo fileinfo = new System.IO.FileInfo("C:\\Windows\\Temp\\file.txt");
try
{
file = fileinfo.OpenWrite();
file.WriteByte(0xF);
}
finally
{
// Check for null because OpenWrite might have failed.
if (file != null)
{
file.Close();
}
}
}
public static void ExceptionTest7()
{
string str = string.Empty;
try
{
int parseInt = int.Parse(str);
}
}
}
public class MyCustomException : Exception
{
public MyCustomException():base("This is my custom exception")
{
}
public MyCustomException(string message) : base($"This is from the method : {message}")
{
}
public MyCustomException(string message, Exception innerException) : base($"Message: {message}, InnerException: {innerException}")
{
}
protected MyCustomException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
}
|
58118f5c52030f08e703d3870a4f7ed5dc40b5f3 | C# | andreialex007/AvitoParser | /AvitoParser.BL/EmailHelper.cs | 2.609375 | 3 | using System;
using System.Collections.Specialized;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using NLog;
namespace AvitoParser.BL
{
public class EmailHelper
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public static NameValueCollection AppSettings;
private static string _smtpServer;
private static int _smtpPort;
private static string _adminEmail;
private static string _loginEmail;
private static string _loginPassword;
private static bool _enableSsl;
private static bool _htmlFormat;
public static void SetConfig(NameValueCollection appSettings)
{
AppSettings = appSettings;
Init();
}
private static void Init()
{
_smtpServer = AppSettings["SmtpServer"];
_smtpPort = Convert.ToInt32(AppSettings["SmtpPort"]);
_loginEmail = AppSettings["LoginEmail"];
_adminEmail = AppSettings["AdminEmail"];
_loginPassword = AppSettings["LoginPassword"];
_enableSsl = Convert.ToBoolean(AppSettings["EnableSSL"]);
_htmlFormat = Convert.ToBoolean(AppSettings["HtmlFormat"]);
}
public static void SendInfoEmail(string subject, string body)
{
Task.Run(() =>
{
SendEmail(subject, body, "AvitoParser@info.ru", "andreialexandrovich@gmail.com");
});
}
public static void SendEmail(string subject, string body, string from, string to)
{
var mailMessage = new MailMessage(from, to, subject, body) { IsBodyHtml = true };
SendEmail(mailMessage);
}
public static void SendEmail(MailMessage message, bool? isHtmlFormat = null)
{
isHtmlFormat = isHtmlFormat ?? _htmlFormat;
message.IsBodyHtml = isHtmlFormat.Value;
DoSendEmail(message);
}
private static void DoSendEmail(MailMessage message)
{
try
{
var client = new SmtpClient(_smtpServer, _smtpPort);
client.EnableSsl = _enableSsl;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(_loginEmail, _loginPassword);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(message);
}
catch (Exception ex)
{
Logger.Debug(ex, "Error while sending email");
}
}
}
} |
ba8807b177217503fd4ee3ebf82a1ab4666cb9cc | C# | mfmese/DesignPatterns | /Observer/Program.cs | 3.546875 | 4 | using System;
using System.Collections.Generic;
namespace Observer
{
/// <summary>
/// Amaç: one-to-many ilişki olan nesnelerde kullanılır. Eğer nesne değişmişse ona bağlı diğer nesneler otomatik olarak bilgilendirilir.
/// Kendine abone olan sistemlerin bir işlem olduğunda devreye girmesini sağlayan bir desendir.
/// </summary>
class Program
{
static void Main(string[] args)
{
ProductManager productManager = new ProductManager();
productManager.Attach(new EmployeeObserver());
productManager.Attach(new CustomerObserver());
productManager.UpdatePrice();
Console.Read();
}
}
class ProductManager
{
List<Observer> _observers = new List<Observer>();
public void UpdatePrice()
{
Console.WriteLine("Product price changed");
Notify();
}
public void Attach(Observer observer)
{
_observers.Add(observer);
}
public void Detach(Observer observer)
{
_observers.Remove(observer);
}
private void Notify()
{
foreach (var observer in _observers)
{
observer.Update();
}
}
}
abstract class Observer
{
public abstract void Update();
}
class CustomerObserver : Observer
{
public override void Update()
{
Console.WriteLine("Message to Customer: Product price updated");
}
}
class EmployeeObserver : Observer
{
public override void Update()
{
Console.WriteLine("Message to Employee: Product price updated");
}
}
}
|
e9d39131c6891890d214c65902a32a6eb347e2fe | C# | keshaavg/game-of-life | /GameOfLife.Tests/CellTest.cs | 3.078125 | 3 | using GameOfLife.Domain;
using System;
using Xunit;
namespace GameOfLife
{
public class CellTest
{
[Theory]
[InlineData('a')]
[InlineData('@')]
public void Throws_ArgumentOutOfRangeException_ForInvalidValues(char cellStatus)
{
// Arrange + Act + Assert
Assert.Throws<ArgumentOutOfRangeException>(() => new Cell(cellStatus));
}
[Theory]
[InlineData('.', '*')]
[InlineData('.')]
[InlineData('.', '.', '.')]
public void WhenActiveCellHas_LessThanTwoNeighbours_CellDies(params char[] neighbours)
{
var sut = new Cell('*');
var result = sut.Evaluate(neighbours);
Assert.Equal('.', result);
}
[Theory]
[InlineData('.', '*', '*', '*', '*')]
[InlineData('.', '*', '*', '*', '*', '*')]
public void WhenActiveCellHas_MoreThanThreeNeighbours_CellDies(params char[] neighbours)
{
var sut = new Cell('*');
var result = sut.Evaluate(neighbours);
Assert.Equal('.', result);
}
[Theory]
[InlineData('.', '*', '*')]
[InlineData('.', '*', '*', '*')]
public void WhenActiveCellHas_TwoOrThreeNeighbours_RemainsActive(params char[] neighbours)
{
var sut = new Cell('*');
var result = sut.Evaluate(neighbours);
Assert.Equal('*', result);
}
[Theory]
[InlineData('.', '*', '*', '*')]
public void WhenDeadCellHas_ExactlyThreeNeighbours_BecomesActive(params char[] neighbours)
{
var sut = new Cell('.');
var result = sut.Evaluate(neighbours);
Assert.Equal('*', result);
}
}
}
|
67cf6740bbebcf3adcb8a5dfd11d5f186c3a8811 | C# | SAW1518/MosbitJesusTraining | /C#/TestPoo/TestPoo/CAsociado.cs | 2.53125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestPoo
{
class CAsociado
{
public CAsociado() {
_Sueldo = "16 000 $";
}
private string _Sueldo;
internal string Puesto {get; set; }
public string Horas { get; set; }
public string Sueldo {
get { return _Sueldo; }
set { _Sueldo = $"{value} $"; }
}
protected void doSomething()
{
//something
}
}
}
|
f777ec1c075ba3563720623b651ba9495654655c | C# | qxc/Blink | /Blink/Assets/Scripts/GameLogger.cs | 2.515625 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class GameLogger : MonoBehaviour
{
// Use this for initialization
public void WriteGameLog(string score, string time)
{
//int pathEnder = Random.Range(0, 1000000);
string path = Application.persistentDataPath;
string file = path + "/Blink.csv";
//Write some text to the test.txt file
StreamWriter writer = new StreamWriter(file, true);
Directory.CreateDirectory(path);
//System.IO.File.WriteAllText(path2+"Blink"+ pathEnder +".txt",System.DateTime.Now + " Score: " + score + " " + "Time: " + time);
writer.WriteLine(System.DateTime.Now + "," + score + "," + time);
writer.Close();
//Print the text from the file
}
private void Start()
{
//Debug.Log(Application.persistentDataPath);
}
}
|
a80ec831d801d9737c94cb5487508101d0627186 | C# | leeleiBruce/HealthyInformations | /HealthyInformation.FrameWork/ActionTrigger/TriggerHelper.cs | 2.515625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Interactivity = System.Windows.Interactivity;
namespace HealthyInformation.FrameWork.ActionTrigger
{
public static class TriggerHelper
{
public static void AttchEventTriggerAction<TViewModel>(this DependencyObject dpObj, BaseTrigger<DependencyObject, TViewModel> triggerAcion, string eventName)
where TViewModel : WindowBase
{
if (dpObj == null || triggerAcion == null || string.IsNullOrEmpty(eventName)) return;
Interactivity.EventTrigger eventTrigger = new Interactivity.EventTrigger(eventName);
eventTrigger.Actions.Add(triggerAcion);
Interactivity.Interaction.GetTriggers(dpObj).Add(eventTrigger);
}
public static void DetachEventTriggerAction(this DependencyObject dpObj)
{
if (dpObj == null) return;
Interactivity.TriggerCollection triggerCollection = Interactivity.Interaction.GetTriggers(dpObj);
if (triggerCollection != null && triggerCollection.Count == 0) return;
foreach (var triggerAction in triggerCollection)
{
triggerAction.Detach();
}
}
}
}
|
ffac0d160a8b6bd8f91970d433633ffd4daee281 | C# | yapyuyou/ICT2106-2018T2-P2 | /SmartHome/Controllers/UsageStatistics/EnergyUsageController.cs | 2.640625 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using SmartHome.Models;
using UsageStatistics.Models;
namespace UsageStatistics.Controllers
{
public class EnergyUsageController : Controller
{
private Session _session;
// GET: EnergyUsage
public ActionResult Index(string location, string type, string timePeriod)
{
_session = Session.getInstance;
if (_session != null)
{
EnergyUsage result = new EnergyUsage();
// gets individal energy usage in kwh and rounding it off to 2dp
ViewBag.sum = Math.Round(result.IndividualEnergyUsage(location, type, timePeriod), 2);
ViewBag.location = location;
return View(result);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
} |
ff158d33429b480a4bf26cf483ebf5d22265bc81 | C# | svetlyoek/DB | /Entity Framework Core/Best practicing and architecture/PetStore/PetStore.Services.Models/Pet/PetCreateServiceModel.cs | 2.625 | 3 | namespace PetStore.Services.Models.Pet
{
using PetStore.Models.Enums;
using System;
using System.ComponentModel.DataAnnotations;
public class PetCreateServiceModel
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
public DateTime Birthdate { get; set; }
[Required]
public AnimalGender Gender { get; set; }
[Required]
[StringLength(250)]
public string Description { get; set; }
[Required]
[Range(1, double.MaxValue, ErrorMessage = "Price must be positive number!")]
public decimal Price { get; set; }
[Required]
[Range(1, int.MaxValue, ErrorMessage = "Id must be more or at least 1!")]
public int BreedId { get; set; }
[Required]
[Range(1, int.MaxValue, ErrorMessage = "Id must be more or at least 1!")]
public int CategoryId { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Id must be more or at least 1!")]
public int? OrderId { get; set; }
}
}
|
7b6d335fdc28b85493f737cad855a3b0395ea1f3 | C# | rhanariba001/ventas | /ventas/Mantenimiento/BL/ClienteBL.cs | 2.765625 | 3 | using Mantenimiento.Modelos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mantenimiento.BL
{
public class ClienteBL
{
public List<Cliente> ListadeCliente { get; set; }
public ClienteBL()
{
ListadeCliente = new List<Cliente>();
CrearDatosdePrueba();
}
private void CrearDatosdePrueba()
{
var ciudad1 = new Ciudad(1, "Puerto Cortes");
var ciudad2 = new Ciudad(2, "San Pedro Sula");
var Cliente1 = new Cliente(1, "Juan Perez","9999-9999","calle JP2",ciudad1);
var Cliente2 = new Cliente(2, "Maria Martinez","8888-8888","7 calle",ciudad2);
ListadeCliente.Add(Cliente1);
ListadeCliente.Add(Cliente2);
}
}
}
|
10badb016e6e3f6635ceca9f1fd06add18b5e039 | C# | MeadowSuite/Meadow | /src/Meadow.EVM/Exceptions/TransactionException.cs | 2.5625 | 3 | using System;
using System.Collections.Generic;
using System.Text;
namespace Meadow.EVM.Exceptions
{
/// <summary>
/// An exception thrown to signal that our transaction was invalid.
/// </summary>
public class TransactionException : Exception
{
public TransactionException() { }
public TransactionException(string message) : base(message) { }
public TransactionException(string message, Exception innerException) : base(message, innerException) { }
public TransactionException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { }
}
}
|
cc685b84461bbeebfd84089d0768352143218ab0 | C# | DTRaich/PM-Semester-4 | /Supernova/Supernova/objects/ProjektDataDummy.cs | 2.5625 | 3 | using Supernova.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace Supernova.objects
{
public class ProjektDataDummy
{
#region fields
public int ProjectID = 0;
#region basisdaten
public int lala;
public string lalaknl;
#endregion
#region costTime
#endregion
#region Risk
#endregion
#region Strategie
#endregion
#endregion
public ProjektDataDummy()
{
}
public bool loadProjectdataintoDummy(int id)
{
bool saveworked = false;
ProjectID = id;
DataLoad dl = new DataLoad();
DataSet projektDataSet = dl.loadWholeProjectData(ProjectID);
if (projektDataSet.Tables[1].Rows.Count > 0)
{
extractProjektData(projektDataSet);
saveworked = true;
}
return saveworked;
}
public bool saveProjectDataToDb()
{
// user speichern
DataSave ds = new DataSave();
bool savingWorked = false;
savingWorked = ds.SaveorUpdateProject(this);
return savingWorked;
}
#region extraxtAndCollect
private void extractProjektData(DataSet projektDataSet)
{
throw new NotImplementedException();
}
#endregion
}
}
|
4ed840af3a08496b5222f69b37d31d3bb460f2ee | C# | HristoSpasov/C-Sharp-Advanced | /06. Exercise Iterators and Comparators/07. Equality Logic/Comparers/PersonComparer.cs | 3.546875 | 4 | using _07.Equality_Logic.Interfaces;
using System;
using System.Collections.Generic;
namespace _07.Equality_Logic.Comparers
{
public class PersonComparer : IEqualityComparer<IPerson>, IComparer<IPerson>
{
public bool Equals(IPerson x, IPerson y)
{
return string.Equals(x.Name, y.Name, StringComparison.InvariantCulture) &&
x.Age.Equals(y.Age);
}
public int GetHashCode(IPerson obj)
{
return obj.Name.GetHashCode() + obj.Age.GetHashCode();
}
public int Compare(IPerson x, IPerson y)
{
if (!string.Equals(x.Name, y.Name, StringComparison.InvariantCulture))
{
return string.Compare(x.Name, y.Name, StringComparison.InvariantCulture);
}
if (!x.Age.Equals(y.Age))
{
return x.Age.CompareTo(y.Age);
}
return 0;
}
}
} |
2744d2665ac1571c6dc65859c349172883656006 | C# | boulosdib/Azure-Sentinel | /.script/tests/KqlvalidationsTests/JsonFilesTestData/DataConnectorFilesLoader.cs | 2.59375 | 3 | using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema.Generation;
using Newtonsoft.Json.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Kqlvalidations.Tests
{
public class DataConnectorFilesLoader : JsonFilesLoader
{
protected override List<string> GetDirectoryPaths()
{
var basePath = Utils.GetTestDirectory(TestFolderDepth);
var solutionDirectories = Path.Combine(basePath, "Solutions");
var dataconnectorDir = Directory.GetDirectories(solutionDirectories, "Data Connectors", SearchOption.AllDirectories);
return dataconnectorDir.ToList();
}
//over ride GetFilesNames method
public override List<string> GetFilesNames()
{
List<string> validFiles = new List<string>();
try
{
var directoryPaths = GetDirectoryPaths();
return directoryPaths.Aggregate(new List<string>(), (accumulator, directoryPath) =>
{
var files = Directory.GetFiles(directoryPath, "*.json", SearchOption.AllDirectories)?.ToList();
if (files != null)
{
files.ForEach(filePath =>
{
try
{
JSchema dataConnectorJsonSchema = JSchema.Parse(File.ReadAllText("DataConnectorSchema.json"));
var jsonString = File.ReadAllText(filePath);
JObject dataConnectorJsonObject = JObject.Parse(jsonString);
if (dataConnectorJsonObject.IsValid(dataConnectorJsonSchema))
{
validFiles.Add(filePath);
}
else
{
throw new Exception("Invalid JSON schema for file: " + filePath);
}
}
catch (JsonReaderException ex)
{
Console.WriteLine("Invalid JSON file: " + filePath);
Console.WriteLine("Error message: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while processing file: " + filePath);
Console.WriteLine("Error message: " + ex.Message);
}
});
}
else
{
Console.WriteLine("No JSON files found in directory: " + directoryPath);
}
return accumulator.Concat(validFiles).ToList();
});
}
catch (Exception ex)
{
Console.WriteLine("An error occurred while retrieving directory paths.");
Console.WriteLine("Error message: " + ex.Message);
}
return validFiles;
}
}
} |
3a10a7dd374e25d4c3282aa7b63598b19f5480c2 | C# | captainanderz/DateFlix-API | /Dateflix-MVC/Services/MessagesService.cs | 2.703125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DateflixMVC.Dtos;
using DateflixMVC.Helpers;
using DateflixMVC.Models.Profile;
namespace DateflixMVC.Services
{
public class MessagesService : IMessageService
{
private WebApiDbContext _context;
public MessagesService(WebApiDbContext context)
{
_context = context;
}
public async Task SaveMessage(string senderUsername, string receiverUsername, string message)
{
if (string.IsNullOrWhiteSpace(message) || string.IsNullOrWhiteSpace(senderUsername) || string.IsNullOrWhiteSpace(receiverUsername))
{
return;
}
var senderUser = _context.Users.AsQueryable().FirstOrDefault(x => x.Email == senderUsername);
var receiverUser = _context.Users.AsQueryable().FirstOrDefault(x => x.Email == receiverUsername);
if (senderUser == null || receiverUser == null)
{
return;
}
await SaveMessage(senderUser, receiverUser.Id, message);
}
public async Task SaveMessage(User sender, int receiverId, string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return;
}
var directMessage = new DirectMessages()
{
SenderId = sender.Id,
ReceiverId = receiverId,
Message = message,
CreatedDate = DateTime.UtcNow
};
_context.DirrectMessages.Add(directMessage);
await _context.SaveChangesAsync();
}
public List<MessageDto> GetMessages(string senderUsername, string receiverUsername, string senderId = null, string receiverId = null)
{
if (senderId == null || receiverId == null)
{
var senderUser = _context.Users.AsQueryable().FirstOrDefault(x => x.Email == senderUsername);
var receiverUser = _context.Users.AsQueryable().FirstOrDefault(x => x.Email == receiverUsername);
if (senderUser == null || receiverUser == null)
{
return null;
}
senderId = senderUser.Id.ToString();
receiverId = receiverUser.Id.ToString();
}
var senderMessages = _context.DirrectMessages.AsQueryable().Where(x => x.SenderId.ToString() == senderId && x.ReceiverId.ToString() == receiverId).ToList();
var receiverMessages = _context.DirrectMessages.AsQueryable().Where(x => x.SenderId.ToString() == receiverId && x.ReceiverId.ToString() == senderId).ToList();
var allMessages = senderMessages;
allMessages.AddRange(receiverMessages);
var ordered = allMessages.OrderBy(x => x.CreatedDate).ToList();
var messageDtos = new List<MessageDto>();
foreach (var directMessage in ordered)
{
messageDtos.Add(new MessageDto()
{
Date = directMessage.CreatedDate,
Message = directMessage.Message,
ReceiverFirstname = receiverId == directMessage.ReceiverId.ToString() ? receiverUsername : senderUsername,
SenderFirstname = senderId == directMessage.SenderId.ToString() ? senderUsername : receiverUsername
});
}
return messageDtos;
}
}
}
|
9b23d95b8c1a7565d3a8c20f8c9b111441f5f351 | C# | smarkets/IronSmarkets | /IronSmarkets/System/Threading/LazyInitializer.cs | 2.578125 | 3 | //
// LazyInitializer.cs
//
// Author:
// Jérémie "Garuma" Laval <jeremie.laval@gmail.com>
//
// Copyright (c) 2009 Jérémie "Garuma" Laval
//
// 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.
using System;
using System.Threading;
namespace IronSmarkets.System.Threading
{
public static class LazyInitializer
{
public static T EnsureInitialized<T> (ref T target) where T : class
{
return EnsureInitialized (ref target, GetDefaultCtorValue<T>);
}
public static T EnsureInitialized<T> (ref T target, Func<T> valueFactory) where T : class
{
if (target == null)
Interlocked.CompareExchange (ref target, valueFactory (), null);
return target;
}
public static T EnsureInitialized<T> (ref T target, ref bool initialized, ref object syncLock)
{
return EnsureInitialized (ref target, ref initialized, ref syncLock, GetDefaultCtorValue<T>);
}
public static T EnsureInitialized<T> (ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
lock (syncLock) {
if (initialized)
return target;
initialized = true;
return target = valueFactory ();
}
}
internal static T GetDefaultCtorValue<T> ()
{
try {
return Activator.CreateInstance<T> ();
} catch {
throw new MissingMemberException ("The type being lazily initialized does not have a "
+ "public, parameterless constructor.");
}
}
internal static T GetDefaultValueFactory<T> ()
{
return default (T);
}
}
}
|
6bdc4d8330643543607124194cd7262b5187902c | C# | Tonic-Box/D3Studio-Source | /D3.Protobuf/Console/PropertyExtension.cs | 2.875 | 3 |
using System;
using System.ComponentModel;
using System.Reflection;
namespace PB.Console
{
public static class PropertyExtension
{
public static void SetPropertyValue(this object obj, string propName, object value)
{
PropertyInfo property = obj.GetType().GetProperty(propName);
Type conversionType = property.PropertyType;
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
{
if (value == null)
{
property.SetValue(obj, (object) null, (object[]) null);
return;
}
conversionType = new NullableConverter(property.PropertyType).UnderlyingType;
}
property.SetValue(obj, Convert.ChangeType(value, conversionType), (object[]) null);
}
public static object GetPropertyValue(this object obj, string propName) => obj.GetType().GetProperty(propName).GetValue(obj, (object[]) null);
}
}
|
96bb63caefca78f8c856d8e44469ca80d8685ddb | C# | CyberBird2/Projects | /C# Projects/RockPaperScissorsLizzardSpock/RockPaperScissorsLizzardSpock/Form1.cs | 2.78125 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RockPaperScissorsLizzardSpock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pbPaper_Click(object sender, EventArgs e)
{
lbResults.Items.Add(game.kagit);
Random rnd = new Random();
int num=rnd.Next(0,3);
lbResults.Items.Add((game)num);
if (game.kagit>(game)num)
{
lbResults.Items.Add("---Win---");
}
if (game.kagit == (game)num)
{
lbResults.Items.Add("---Equal---");
}
if (game.kagit < (game)num)
{
lbResults.Items.Add("---Loose---");
}
}
private void pbRock_Click(object sender, EventArgs e)
{
lbResults.Items.Add(game.tas);
Random rnd = new Random();
int num = rnd.Next(0,2);
lbResults.Items.Add((game)num);
}
private void pbScissors_Click(object sender, EventArgs e)
{
lbResults.Items.Add(game.makas);
Random rnd = new Random();
int num = rnd.Next(0, 2);
lbResults.Items.Add((game)num);
}
//public void search(isActive aa)
//{
// if (aa==isActive.all)
// {
// }
//}
//public void search(int aa)
//{
// if (aa == 0)
// {
// }
//}
//public enum isActive
//{
// all = 0,
// onlyActive = 1,
// onlyPassive = 2
//}
public enum game
{
tas=0,
kagit=1,
makas=2
}
}
}
|
1a8bbb7e60605dfd2b4234517bf319b9d1512132 | C# | Jafic/EZNEW | /EZNEW/Extensions/GuidExtensions.cs | 3.578125 | 4 | namespace System
{
/// <summary>
/// Guid extensions
/// </summary>
public static class GuidExtensions
{
#region Verify guid vlaue whether is empty
/// <summary>
/// Verify Guid is empty or not
/// </summary>
/// <param name="value">Guid value</param>
/// <returns>Return whether value is empty</returns>
public static bool IsEmpty(this Guid value)
{
return value.Equals(Guid.Empty);
}
#endregion
#region Convert Guid to Int64
/// <summary>
/// Convert Guid to Int64
/// </summary>
/// <param name="value">Guid value</param>
/// <returns>Return the int64 value</returns>
public static long ToInt64(this Guid value)
{
byte[] bytes = value.ToByteArray();
return BitConverter.ToInt64(bytes, 0);
}
#endregion
#region Convert Guid to Int32
/// <summary>
/// Convert Guid to Int32
/// </summary>
/// <param name="value">Guid value</param>
/// <returns>Return the int32 value</returns>
public static int ToInt32(this Guid value)
{
byte[] bytes = value.ToByteArray();
return BitConverter.ToInt32(bytes, 0);
}
#endregion
#region Convert guid to uniquecode(formatting to upper)
/// <summary>
/// Convert guid to uniquecode(formatting to upper)
/// </summary>
/// <param name="value">Guid value</param>
/// <returns>Return the uniquecode value</returns>
public static string ToUniqueCode(this Guid value)
{
long i = 1;
byte[] bytes = value.ToByteArray();
foreach (byte b in bytes)
{
i *= (b + 1);
}
string code = string.Format("{0:x}", i - DateTimeOffset.Now.Ticks);
return code;
}
#endregion
}
}
|
fc70d08dabe996b9ef002e0960147e3f21be7796 | C# | dobroslav-atanasov/Programming-Fundamentals | /13. ArraysAndMethods-MoreExercises/06. Heists/Heists.cs | 3.671875 | 4 | using System;
using System.Collections.Generic;
using System.Linq;
namespace _06.Heists
{
public class Heists
{
static void Main()
{
int[] prices = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int priceJewels = prices[0];
int priceGold = prices[1];
string input = Console.ReadLine();
long heistExpenses = 0;
long totalEarnings = 0;
while (!input.Equals("Jail Time"))
{
string[] inputParts = input.Split(' ').ToArray();
char[] loots = inputParts[0].ToCharArray();
heistExpenses += int.Parse(inputParts[1]);
for (int i = 0; i < loots.Length; i++)
{
if (loots[i].Equals('%'))
{
totalEarnings += priceJewels;
}
else if (loots[i].Equals('$'))
{
totalEarnings += priceGold;
}
}
input = Console.ReadLine();
}
if (totalEarnings >= heistExpenses)
{
Console.WriteLine($"Heists will continue. Total earnings: {totalEarnings - heistExpenses}.");
}
else
{
Console.WriteLine($"Have to find another job. Lost: {heistExpenses - totalEarnings}.");
}
}
}
}
|
1df30a31e6f5fe4f27a7bcd2bd9cac8ad133c6ee | C# | jasiak96336/test | /Form1.cs | 2.71875 | 3 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace jak_się_czujesz_xd
{
public partial class Form1 : Form
{
int nastroj = 0;
int pyt =0;
public Form1()
{
InitializeComponent();
}
private void pytanie_Click(object sender, EventArgs e)
{
}
private void odp1_Click(object sender, EventArgs e)
{
pyt++;
if (pyt > 0)
{
odp1.Text = "Tak";
odp2.Text = "Nie";
}
if (pyt ==1)
{
pytanie.Text = "Wyspałeś/aś się dziś?";
nastroj++;
}
if (pyt == 2)
{
pytanie.Text = "Zjadłeś/aś śniadanie?";
nastroj++;
}
if (pyt == 3)
{
pytanie.Text = "Spotkało Cię coś miłego?";
nastroj++;
}
if (pyt == 4)
{
pytanie.Text = "Odczuwasz jakiś ból?";
}
if (pyt == 5)
{
pytanie.Text = "Zobaczyłeś/aś dziś coś śmiesznego?";
nastroj++;
}
if (pyt == 6)
{
pytanie.Text = "Obiadek był smaczny?";
nastroj++;
}
if (pyt == 7)
{
pytanie.Text = "Zdenerwował Cię ktoś dzisiaj?";
}
if (pyt == 8)
{
pytanie.Text = "Powiedział Ci ktoś coś miłego?";
nastroj++;
}
if (pyt == 9)
{
pytanie.Text = "Słuchałeś/aś swojej ulubionej muzyki?";
nastroj++;
}
if (pyt == 10)
{
pytanie.Text = "Zostałeś/aś do czegoś zmuszony/a?";
}
if (pyt > 10)
{
odp1.Text = "Podsumuj ankietę!";
if (nastroj > 5)
{
Form3 f = new Form3();
f.ShowDialog();
}
odp2.Text = "Nie chcę znać wyniku";
}
}
private void odp2_Click(object sender, EventArgs e)
{
pyt++;
if (pyt > 0)
{
odp1.Text = "Tak";
odp2.Text = "Nie";
}
if (pyt == 1)
{
pytanie.Text = "Wyspałeś/aś się dziś?";
}
if (pyt == 2)
{
pytanie.Text = "Zjadłeś/aś śniadanie?";
}
if (pyt == 3)
{
pytanie.Text = "Spotkało Cię coś miłego?";
}
if (pyt == 4)
{
pytanie.Text = "Odczuwasz jakiś ból?";
}
if (pyt == 5)
{
pytanie.Text = "Zobaczyłeś/aś dziś coś śmiesznego?";
}
if (pyt == 6)
{
pytanie.Text = "Obiadek był smaczny?";
}
if (pyt == 7)
{
pytanie.Text = "Zdenerwował Cię ktoś dzisiaj?";
}
if (pyt == 8)
{
pytanie.Text = "Powiedział Ci ktoś coś miłego?";
}
if (pyt == 9)
{
pytanie.Text = "Słuchałeś/aś swojej ulubionej muzyki?";
}
if (pyt == 10)
{
pytanie.Text = "Zostałeś/aś do czegoś zmuszony/a?";
}
if (pyt > 10)
{
odp1.Text = "Podsumuj ankietę!";
odp2.Text = "Nie chcę znać wyniku";
}
}
}
}
|
6832c9dbe422ea9c4be0d5e7b5b19bbd5cf6a2db | C# | AStrand94/WebApplikasjoner | /DAL1/Stub/CustomerStub.cs | 2.828125 | 3 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebApplication3.Model;
namespace WebApplication3.DAL
{
public class CustomerStub : ICustomerDAL
{
public Customer AddCustomer(Customer customer)
{
if (customer.Id == 0)
{
var c = new Customer
{
Id = 0
};
return c;
}
else
{
return GetCustomer(1);
}
}
public Order DeleteAssociatedOrder(int customerId, int orderId)
{
var o = new Order
{
Id = 1
};
return o;
}
public Customer DeleteCustomer(int id)
{
if (id == 0)
{
return null;
}
else
{
return GetCustomer(1);
}
}
public bool ExistsCustomerWithId(int customerId)
{
if (customerId == 100)
{
return true;
}
else
{
return false;
}
}
public IEnumerable<Customer> GetAllCustomers()
{
var customerList = new List<Customer>();
var customer = GetCustomer(1);
customerList.Add(customer);
customerList.Add(customer);
customerList.Add(customer);
return customerList;
}
public IEnumerable<Customer> GetAllCustomersConnections()
{
var customerList = new List<Customer>();
var customer = GetCustomer(1);
customerList.Add(customer);
customerList.Add(customer);
customerList.Add(customer);
return customerList;
}
public Customer GetCustomer(int id)
{
var customer = new Customer()
{
Id = 1,
Firstname = "Ola",
Lastname = "Normann",
Email = "olanormann@gmail.com",
Telephone = "12345678"
};
return customer;
}
public bool HasOrder(int id)
{
if (id == 100)
{
return false;
}
else
{
return true;
}
}
public Customer UpdateCustomer(Customer customer)
{
if (customer.Id == 0)
{
var c = new Customer
{
Id = 0
};
return c;
}
else
{
return GetCustomer(1);
}
}
}
}
|
b6b8c9ef013be244dd4d3673aab79b69454f9937 | C# | Anrich96/Anoroc-Server | /Anoroc-User-Management/Models/Cluster/ClusterWrapper.cs | 2.6875 | 3 | using Microsoft.AspNetCore.Routing.Constraints;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Anoroc_User_Management.Models
{
/// <summary>
/// Class used to simplify the clusters so that we don't send too much data to the Mobile app.
/// </summary>
public class ClusterWrapper
{
public ClusterWrapper(DateTime _created, int pins, int carrier, double radius, Location center)
{
Pin_Count = pins;
Carrier_Pin_Count = carrier;
Cluster_Radius = radius;
Center_Pin = center;
Created = _created;
}
/// <summary>
/// Attributes used to store cluster information
/// </summary>
/// <param name="Pin_Count"> number of locations in the cluster </param>
/// <param name="Carrier_Pin_Count"> number of contagent carrier location points in the cluster </param>
/// <param name="Cluster_Radius"> max (distance between any two points in the cluster) </param>
/// <param name="Center_Pin"> Location variable of the center pin in the cluster</param>
public int Pin_Count { get; set; }
public int Carrier_Pin_Count { get; set; }
public double Cluster_Radius { get; set; }
public Location Center_Pin { get; set; }
public DateTime Created { get; set; }
}
}
|
7906740c6c65dbd09040d1147140b1baaf32e2c2 | C# | SynHub/syn-speech | /Syn.Speech/Trainer/Node.cs | 3.15625 | 3 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Syn.Speech.Trainer
{
/// <summary>
/// Defines the basic Node for any graph A generic graph Node must have a list of outgoing edges and an identifier.
/// </summary>
public class Node
{
// Do we really need nodeId and object? Maybe we can use object as
// the id when we assign a string to it.
/// <summary>
/// The identifier for this Node
/// </summary>
private readonly string nodeId;
/// <summary>
/// Object contained in this mode. Typically, an HMM state, a senone.
/// </summary>
private Object _object;
/** The type of node, such as a dummy node or node represented by a specific type of symbol */
private readonly NodeType nodeType;
/** The list of incoming edges to this node. */
private readonly List<Edge> incomingEdges;
private Edge incomingEdgeIterator;
/** The list of outgoing edges from this node */
private readonly List<Edge> outgoingEdges;
private Edge outgoingEdgeIterator;
/**
/// Constructor for node when a type and symbol are given.
*
/// @param nodeType the type of node.
/// @param nodeSymbol the symbol for this type.
*/
Node(NodeType nodeType, string nodeSymbol)
{
incomingEdges = new List<Edge>();
outgoingEdges = new List<Edge>();
nodeId = nodeSymbol;
this.nodeType = nodeType;
_object = null;
}
/**
/// Constructor for node when a type only is given.
*
/// @param nodeType the type of node.
*/
Node(NodeType nodeType) :this(nodeType, null)
{
}
/**
/// Assign an object to this node.
*
/// @param object the object to assign
*/
public void setObject(Object pobject)
{
_object = pobject;
}
/**
/// Retrieves the object associated with this node.
*
/// @return the object
*/
public Object getObject()
{
return _object;
}
/**
/// Method to add an incoming edge. Note that we do not check if the destination node of the incoming edge is
/// identical to this node
*
/// @param edge the incoming edge
*/
public void addIncomingEdge(Edge edge)
{
incomingEdges.Add(edge);
}
/** Start iterator for incoming edges. */
public void startIncomingEdgeIterator()
{
incomingEdgeIterator = incomingEdges.First();
}
/**
/// Whether there are more incoming edges.
*
/// @return if true, there are more incoming edges
*/
public Boolean hasMoreIncomingEdges()
{
return incomingEdges.IndexOf(incomingEdgeIterator) < incomingEdges.Count;
}
/**
/// Returns the next incoming edge to this node.
*
/// @return the next edge incoming edge
*/
public Edge nextIncomingEdge()
{
if (!hasMoreIncomingEdges())
return incomingEdgeIterator;
incomingEdgeIterator = incomingEdges[incomingEdges.IndexOf(incomingEdgeIterator) +1];
return incomingEdgeIterator;
}
/**
/// Returns the size of the incoming edges list.
*
/// @return the number of incoming edges
*/
public int incomingEdgesSize()
{
return incomingEdges.Count;
}
/**
/// Method to add an outgoing edge. Note that we do not check if the source node of the outgoing edge is identical to
/// this node
*
/// @param edge the outgoing edge
*/
public void addOutgoingEdge(Edge edge)
{
outgoingEdges.Add(edge);
}
/** Start iterator for outgoing edges. */
public void startOutgoingEdgeIterator()
{
outgoingEdgeIterator = outgoingEdges.First();
}
/**
/// Whether there are more outgoing edges.
*
/// @return if true, there are more outgoing edges
*/
public Boolean hasMoreOutgoingEdges()
{
return outgoingEdges.IndexOf(outgoingEdgeIterator) < outgoingEdges.Count;
}
/**
/// Returns the next outgoing edge from this node.
*
/// @return the next outgoing edge
*/
public Edge nextOutgoingEdge()
{
if (!hasMoreOutgoingEdges())
return outgoingEdgeIterator;
outgoingEdgeIterator = outgoingEdges[outgoingEdges.IndexOf(outgoingEdgeIterator) + 1];
return outgoingEdgeIterator;
}
/**
/// Returns the size of the outgoing edges list.
*
/// @return the number of outgoing edges
*/
public int outgoingEdgesSize()
{
return outgoingEdges.Count;
}
/**
/// Method to check the type of a node.
*
/// @return if true, this node is of the type specified
*/
public Boolean isType(String type)
{
return (type.Equals(nodeType.ToString()));
}
/**
/// Returns type of a node.
*
/// @return returns the type of this node
*/
public NodeType getType()
{
return nodeType;
}
/**
/// Returns the ID of a node. Typically, a string representing a word or a phoneme.
*
/// @return this node's ID
*/
public string getID()
{
return nodeId;
}
/**
/// Validade node. Checks if all nodes have at least one incoming and one outgoing edge.
*
/// @return if true, node passed validation
*/
public Boolean validate()
{
Boolean passed = true;
if (isType("WORD") || isType("PHONE")) {
if (nodeId == null)
{
Debug.Print("Content null in a WORD node.");
passed = false;
}
}
if ((incomingEdgesSize() == 0) && (outgoingEdgesSize() == 0))
{
Debug.Print("Node not connected anywhere.");
passed = false;
}
return passed;
}
/** Prints out this node. */
public void print()
{
Debug.Print("ID: " + nodeId);
Debug.Print(" Type: " + nodeType + " | ");
for (startIncomingEdgeIterator();
hasMoreIncomingEdges();) {
Debug.Print(nextIncomingEdge() + " ");
}
Debug.Print(" | ");
for (startOutgoingEdgeIterator();
hasMoreOutgoingEdges();) {
Debug.Print(nextOutgoingEdge() + " ");
}
Debug.Print("\n");
}
}
}
|
3c0a862a4702234260a2f59f2cb717f35313ed89 | C# | lemonine/Flat | /RandomHelper.cs | 3.09375 | 3 | using System;
using Microsoft.Xna.Framework;
namespace Flat
{
public static class RandomHelper
{
private static Random Rand = new Random();
public static int RandomInteger()
{
return Rand.Next();
}
public static int RandomInteger(Random rand)
{
return rand.Next();
}
public static int RandomInteger(int min, int max)
{
if(min == max)
{
return min;
}
if (min > max)
{
FlatUtil.Swap(ref min, ref max);
}
int result = min + Rand.Next() % (max - min);
return result;
}
public static int RandomInteger(Random rand, int min, int max)
{
if (min > max)
{
FlatUtil.Swap(ref min, ref max);
}
int result = min + rand.Next() % (max - min);
return result;
}
public static bool RandomBooleon()
{
int value = RandomHelper.RandomInteger(0, 2);
if(value == 0)
{
return false;
}
else
{
return true;
}
}
public static float RandomSingle()
{
return (float)Rand.NextDouble();
}
public static float RandomSingle(Random rand)
{
return (float)rand.NextDouble();
}
public static float RandomSingle(float min, float max)
{
if (min > max)
{
FlatUtil.Swap(ref min, ref max);
}
float result = min + (float)Rand.NextDouble() * (max - min);
return result;
}
public static float RandomSingle(Random rand, float min, float max)
{
if (min > max)
{
FlatUtil.Swap(ref min, ref max);
}
float result = min + (float)rand.NextDouble() * (max - min);
return result;
}
public static Color RandomColor()
{
Color result = new Color((float)Rand.NextDouble(), (float)Rand.NextDouble(), (float)Rand.NextDouble());
return result;
}
public static Color RandomColor(Random rand)
{
Color result = new Color((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
return result;
}
public static Color RandomColor(float brightness)
{
// https://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx
// brightness = sqrt( .241 R^2 + .691 G^2 + .068 B^2 )
brightness = FlatMath.Clamp(brightness, 0f, 1f);
float r = RandomHelper.RandomSingle(0f, 1f);
float g = RandomHelper.RandomSingle(0f, 1f);
float b = RandomHelper.RandomSingle(0f, 1f);
float dec = 0.98f;
float inc = 1f / dec;
for(int i = 0; i < 64; i++)
{
float perceivedBrightness = FlatUtil.PercievedBrightness(r, g, b);
if(perceivedBrightness < brightness)
{
r *= inc;
g *= inc;
b *= inc;
}
else if(perceivedBrightness > brightness)
{
r *= dec;
g *= dec;
b *= dec;
}
dec += 0.0001f;
inc -= 0.0001f;
if(dec > 1f) { dec = 1f; }
if(inc < 1f) { inc = 1f; }
}
return new Color(r, g, b);
}
public static Vector2 RandomDirection()
{
float angle = RandomSingle(0, MathHelper.TwoPi);
Vector2 result = new Vector2(MathF.Cos(angle), MathF.Sin(angle));
return result;
}
public static Vector2 RandomDirection(Random rand)
{
float angle = RandomSingle(rand, 0, MathHelper.TwoPi);
Vector2 result = new Vector2(MathF.Cos(angle), MathF.Sin(angle));
return result;
}
}
}
|
90bd45bff2824f04353e72aa60ab6b625f3f1e8e | C# | aosoft/libavif-sharp | /libavif-sharp/AvifImageData.cs | 2.890625 | 3 | using System;
using System.Collections.Generic;
using System.Text;
namespace LibAvif
{
public readonly ref struct AvifImageData<T> where T : unmanaged
{
private readonly AvifData<byte> _data;
public AvifImageData(uint channelCount, uint width, uint height, IntPtr p, uint rowBytes)
{
ChannelCount = channelCount;
Width = width;
Height = height;
RowBytes = rowBytes;
_data = new AvifData<byte>(p, height * rowBytes);
}
unsafe public IntPtr Pointer => _data.Pointer;
public uint ChannelCount { get; }
public uint Width { get; }
public uint Height { get; }
public uint RowBytes { get; }
public AvifData<T> this[uint y]
{
get
{
if (y >= Height)
{
throw new ArgumentOutOfRangeException();
}
unsafe
{
return new AvifData<T>(new IntPtr((byte*)_data.Pointer + RowBytes * y), Width * ChannelCount);
}
}
}
}
}
|
d842d02ddec533c61ef48de0cea399ef248d9689 | C# | Gentlet/Team.NULL-DungeonMusician | /던전 뮤지션/Assets/0_Test/Broken_Fire_Egg/Scripts/MultiObjectAnimation.cs | 2.515625 | 3 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MultiObjectAnimation : MonoBehaviour {
public Animator[] animators;
public string triggerName;
private void Start()
{
TriggerAll();
}
public void TriggerAll()
{
foreach(Animator anitor in animators)
{
anitor.SetTrigger(triggerName);
}
}
public void TriggerOne(int n)
{
animators[n].SetTrigger(triggerName);
}
public void SetDefaultAll()
{
foreach (Animator anitor in animators)
{
anitor.SetTrigger("Default");
}
}
}
|
df176610ea4ea8ff27231ef39d809f8db0aef00c | C# | ProtonSoftware/Pogodeo24 | /Backend/Pogodeo.Core/Commons/OperationResult.cs | 2.953125 | 3 | using System.Collections.Generic;
using System.Text;
namespace Pogodeo.Core
{
/// <summary>
///
/// </summary>
public class OperationResult
{
#region Public Properties
public List<Error> Errors { get; set; }
public bool Success { get; private set; }
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public OperationResult()
{
Success = false;
Errors = new List<Error>();
}
public OperationResult(bool success)
{
this.Success = success;
}
public OperationResult(string error)
{
this.Success = false;
this.Errors = new List<Error>()
{
new Error()
{
Message = error,
}
};
}
public OperationResult(string error, string classification = null, string identyfication = null)
{
this.Success = false;
this.Errors = new List<Error>()
{
new Error()
{
Message = error,
Classification = classification,
Identification = identyfication,
}
};
}
#endregion
public override string ToString()
{
var result = new StringBuilder();
foreach (var error in Errors)
{
if (result.Length > 0)
{
result.Append(", ");
}
result.Append(error.Message);
}
return result.ToString();
}
public void Merge(OperationResult another)
{
this.Success &= another.Success;
this.Errors.AddRange(another.Errors);
}
public OperationResult Error(string message, string identification = null, string classification = null)
{
Errors.Add(new Error()
{
Message = message,
Identification = identification,
Classification = classification,
});
return this;
}
}
public class OperationResult<TResult> : OperationResult
{
public TResult Result { get; set; }
public OperationResult() : base()
{ }
public OperationResult(OperationResult operation, TResult result)
: this(operation.Success, result)
{
Errors = operation.Errors;
}
public OperationResult(bool success)
: base(success)
{ }
public OperationResult(bool success, TResult result)
: base (success)
{
Result = result;
}
public OperationResult(string error)
: base(false)
{
Errors = new List<Error>()
{
new Error()
{
Message = error,
}
};
}
public OperationResult(string error, string classification = null, string identyfication = null)
: base(false)
{
Errors = new List<Error>()
{
new Error()
{
Classification = classification,
Message = error,
Identification = identyfication,
}
};
}
public OperationResult<TResult> WithResult(TResult result)
{
Result = result;
return this;
}
}
}
|
726ada91df273a2fd0a50d882c0674bd709b3d3f | C# | osamajaved/maxsum | /MaxSumTriangle/Input.cs | 3.5 | 4 | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace MaxSumTriangle
{
public static class Input
{
public static async Task<List<string[]>> ReadLines(string path)
{
try
{
StreamReader file = new StreamReader(path);
string line;
var triangle = new List<string[]>();
while ((line = await file.ReadLineAsync()) != null)
{
triangle.Add(line.Trim().Split(' '));
}
return triangle;
}
catch (Exception ex)
{
return null;
}
}
}
}
|
1c84038c53062dda2ee4135725e4df5758020aa0 | C# | JasinskiLuk/TestingProject | /TestingProject.DTOs/ParameterDTO.cs | 2.515625 | 3 | namespace TestingProject.DTOs
{
public class ParameterDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public class NullParameterDTO : ParameterDTO
{
public NullParameterDTO()
{
Id = -1;
Name = "Empty";
Value = "Empty";
}
}
}
|
79c94443952dd81bf0177f13313e28362e41275b | C# | ZyshchykMaksim/nlayer-architecture.net | /NLayer.HealthCheck/HealthChecker.cs | 2.671875 | 3 | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using NLayer.HealthCheck.Models.Enums;
using NLayer.HealthCheck.Models.Results;
using NLayer.Logging;
namespace NLayer.HealthCheck
{
/// <summary>
/// HealthChecker.
/// </summary>
/// <seealso cref="IHealthChecker" />
public sealed class HealthChecker : IHealthChecker
{
private readonly ILog<HealthChecker> logger;
private readonly TimeSpan timeout;
/// <summary>
/// Initializes a new instance of the <see cref="HealthChecker" /> class.
/// </summary>
/// <param name="logFactory">The logger.</param>
public HealthChecker(ILogFactory logFactory)
{
logger = logFactory.CreateLogger<HealthChecker>();
this.timeout = TimeSpan.FromSeconds(5);
}
/// <summary>
/// Checks the specified health check tasks.
/// </summary>
/// <param name="healthChecks">The health checks.</param>
/// <returns></returns>
/// <exception cref="System.InvalidOperationException">At least one HealthCheck should be provided.</exception>
public OveralHealthCheckResult Check(IList<IHealthCheck> healthChecks)
{
if (healthChecks == null || !healthChecks.Any())
{
throw new InvalidOperationException("At least one HealthCheck should be provided.");
}
var individualResults = healthChecks
.AsParallel()
.AsUnordered()
.Select(IndividualHealthCheck)
.OrderBy(r => r.HealthCheckName)
.ToList();
var overalStatus = individualResults.Any(e => !e.IsSucceed) ?
individualResults.Any(e => !e.IsSucceed && e.CriticalMarking == CriticalMarking.High) ?
HealthCheckStatus.Error :
HealthCheckStatus.Warning :
HealthCheckStatus.Healthy;
return new OveralHealthCheckResult(overalStatus, individualResults);
}
private BaseIndividualHealthCheckResult IndividualHealthCheck(IHealthCheck healthCheck)
{
var healthCheckName = healthCheck.GetType().Name;
var sw = Stopwatch.StartNew();
var task = Task.Run<BaseIndividualHealthCheckResult>(
() =>
{
try
{
healthCheck.Check();
}
catch (Exception ex)
{
logger.Error($"Health check { healthCheckName} ({ healthCheck.Description}) error.", ex);
return new FailedIndividualHealthCheckResult(
healthCheckName,
healthCheck.Description,
ex.Message,
healthCheck.CriticalMarking,
sw.Elapsed
);
}
finally
{
sw.Stop();
}
return new SuccessfulIndividualHealthCheckResult(
healthCheckName,
healthCheck.Description,
healthCheck.CriticalMarking,
sw.Elapsed
);
}
);
var isTaskCompletedInTime = Task.WaitAll(new Task[] { task }, timeout);
if (!isTaskCompletedInTime)
{
logger.Error($"Health check {healthCheckName} ({healthCheck.Description}) timed out.");
return new FailedIndividualHealthCheckResult(
healthCheckName,
healthCheck.Description,
"Health check timed out.",
healthCheck.CriticalMarking,
sw.Elapsed
);
}
return task.Result;
}
}
}
|
7b51056543407b8b5c877d942bd35d9bad61dc5f | C# | albertosam/ffb-tec-inter | /TrilhasCertificacao/Infrastructure/Repositories/CertificadoRepository.cs | 2.671875 | 3 | using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TrilhasCertificacao.Domain;
using TrilhasCertificacao.Infrastructure;
namespace TrilhasCertificacao.Infrastructure.Repositories
{
public class CertificadoRepository : ICertificadoRepository
{
private readonly TrilhaContext _context;
public CertificadoRepository(TrilhaContext trilhaContext)
{
_context = trilhaContext;
}
public async Task<Certificacao> AddAsync(Certificacao entity)
{
await _context.Certificacoes.AddAsync(entity);
await _context.SaveChangesAsync();
return entity;
}
public async Task DeleteAsync(Guid id)
{
var ent = await GetAsync(id);
_context.Remove(ent);
await _context.SaveChangesAsync();
}
public Task<List<Certificacao>> GetAllAsync()
{
return _context.Certificacoes.ToListAsync();
}
public async Task<Certificacao> GetAsync(Guid id)
{
return await _context.Certificacoes
.Where(x => x.Id == id)
.FirstOrDefaultAsync();
}
public async Task<Certificacao> UpdateAsync(Certificacao entity)
{
var entityDatabase = await GetAsync(entity.Id);
_context.Entry(entityDatabase).CurrentValues.SetValues(entity);
await _context.SaveChangesAsync();
return entity;
}
}
}
|
a089a652612b387aa25f5e20e366712102d72ec5 | C# | alialwahish/WizardNinjaSamurai | /Samurai.cs | 2.78125 | 3 | namespace Human{
public class Samurai : Human{
public Samurai(string samuraiName):base(samuraiName){
this.health=200;
}
public void death_blow(Human rhs){
if(rhs.health<=50){
rhs.health=0;
}
else{
rhs.health-=50;
}
}
public void meditate(){
this.health=200;
}
}
} |
428637e6ab0d5ab49f6fb9b5ea3d74a8f09e3339 | C# | VKeCRM/V2 | /Framework/VKeCRM.Common/Cryptography/RsaCryptoProvider.cs | 2.8125 | 3 | //-----------------------------------------------------------------------
// <copyright file="RsaCryptoProvider.cs" company="VKeCRM">
// Company copyright tag.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using VKeCRM.Common.Messages;
namespace VKeCRM.Common.Cryptography
{
/// <summary>
/// Rsa Crypto Provider base class
/// </summary>
public abstract class RsaCryptoProvider : ICryptoProvider
{
#region Constants
/// <summary>
/// RSA Block size
/// </summary>
private const int RSABLOCKSIZE = 256;
/// <summary>
/// Size for splitting RSA block
/// </summary>
private const int SPLITBLOCKSIZE = 32;
#region ICryptoProvider Members
/// <summary>
/// Encrypts a stream of data.
/// </summary>
/// <param name="stream">Stream to encrypt.</param>
/// <returns>Array containing encrypted bytes from the stream.</returns>
byte[] ICryptoProvider.Encrypt(Stream stream)
{
RSACryptoServiceProvider csp = Load();
byte[][] byteBlockArray = SplitBytes(GetStreamBytes(stream), SPLITBLOCKSIZE);
byte[] bytes = new byte[byteBlockArray.Length * RSABLOCKSIZE];
int offset = 0;
for (int j = 0; j < byteBlockArray.Length; j++)
{
offset = CopyBytes(csp.Encrypt(byteBlockArray[j], true), bytes, offset);
}
return bytes;
}
/// <summary>
/// Decrypts a stream of data.
/// </summary>
/// <param name="stream">Stream to encrypt.</param>
/// <returns>Array containing encrypted bytes from the stream.</returns>
byte[] ICryptoProvider.Decrypt(Stream stream)
{
StringBuilder result = new StringBuilder();
byte[] streamBytes = GetStreamBytes(stream);
if (streamBytes.Length > 0)
{
RSACryptoServiceProvider csp = Load();
byte[][] byteBlockArray = SplitBytes(GetStreamBytes(stream), RSABLOCKSIZE);
for (int j = 0; j < byteBlockArray.Length; j++)
{
result.Append(ASCIIEncoding.UTF8.GetString(csp.Decrypt(byteBlockArray[j], true)));
}
}
return ASCIIEncoding.UTF8.GetBytes(result.ToString());
}
#endregion
#endregion // Constants
#region Open/Load Methods
/// <summary>
/// Loads named container from the store.
/// </summary>
/// <returns>A new RSACryptoServiceProvider instance initialized retrieved from the cryptography store.</returns>
public abstract RSACryptoServiceProvider Load();
/// <summary>
/// Loads container from an Xml file.
/// </summary>
/// <returns>
/// <para>
/// A new RSACryptoServiceProvider instance initialized using the public key parameters
/// from the specified public key file name.
/// </para>
/// </returns>
/// <remarks>Throws FileNotFound exception if the public key file cannot be found.</remarks>
public abstract RSACryptoServiceProvider Open();
/// <summary>
/// Loads container from an Xml file.
/// </summary>
/// <param name="openPrivateKey">
/// If true, the parameters are loaded from the specified private key file.
/// </param>
/// <returns>
/// <para>
/// A new RSACryptoServiceProvider instance initialized using the parameters
/// from the either the public or the public/private key file name.
/// </para>
/// </returns>
/// <remarks>Throws FileNotFound exception if the public key file cannot be found.</remarks>
public abstract RSACryptoServiceProvider Open(bool openPrivateKey);
#endregion // Open/Load Methods
#region Static Helper Methods
/// <summary>
/// To convert to RSA Key size
/// </summary>
/// <param name="keySize">Size of key</param>
/// <returns>Returns a RSA key size</returns>
internal static RsaKeySize ConvertToRSAKeySize(int keySize)
{
RsaKeySize result = RsaKeySize.Unknown;
switch (keySize)
{
case 512:
result = RsaKeySize.Bits512;
break;
case 1024:
result = RsaKeySize.Bits1024;
break;
case 2048:
result = RsaKeySize.Bits2048;
break;
case 4096:
result = RsaKeySize.Bits4096;
break;
case 8192:
result = RsaKeySize.Bits8192;
break;
case 16384:
result = RsaKeySize.Bits16384;
break;
}
return result;
}
/// <summary>
/// To get stream bytes
/// </summary>
/// <param name="stream">Stream to convert to bytes</param>
/// <returns>Returns a byte array</returns>
protected static byte[] GetStreamBytes(Stream stream)
{
// Allocate the buffer
byte[] result = new byte[stream.Length];
// Reset stream position
stream.Seek(0, SeekOrigin.Begin);
// Read Steam Contents
if (stream.Read(result, 0, result.Length) != result.Length)
{
throw new IOException(ErrorMessages.StreamReadError);
}
return result;
}
/// <summary>
/// Split a source array to a double dimensional byte array
/// </summary>
/// <param name="source">Source array</param>
/// <param name="blocksize">Size of blocks to split source into</param>
/// <returns>Returns a double dimensional byte array</returns>
protected static byte[][] SplitBytes(byte[] source, int blocksize)
{
int numberOfBlocks = (source.Length < blocksize) ? 1 : (source.Length / blocksize);
byte[][] byteBlockArray = new byte[numberOfBlocks][];
int offset = 0;
for (int i = 1; i <= numberOfBlocks; i++)
{
if (i == numberOfBlocks)
{
byteBlockArray[i - 1] = CloneBytes(source, offset, source.Length - offset);
}
else
{
byteBlockArray[i - 1] = CloneBytes(source, offset, blocksize);
offset += blocksize;
}
}
return byteBlockArray;
}
/// <summary>
/// To copy bytes from source to target
/// </summary>
/// <param name="source">Source of bytes to copy from</param>
/// <param name="target">Target for bytes to be copied into</param>
/// <param name="offset">Off set of bytes to copy</param>
/// <returns>Returns the number of bytes copied</returns>
protected static int CopyBytes(byte[] source, byte[] target, int offset)
{
Array.Copy(source, 0, target, offset, source.Length);
return offset + source.Length;
}
/// <summary>
/// To clone bytes
/// </summary>
/// <param name="source">Source of bytes to clone</param>
/// <param name="offset">Off set of bytes for cloning</param>
/// <param name="size">Size of bytes to clone</param>
/// <returns>Returns a byte array that is a clone of the source</returns>
protected static byte[] CloneBytes(byte[] source, int offset, int size)
{
byte[] result = new byte[size];
Array.Copy(source, offset, result, 0, size);
return result;
}
#endregion // Static Helper Methods
}
} |
caac968358b651655eaaeff0d9f666bc87a94276 | C# | shendongnian/download4 | /first_version_download2/264573-21145794-55722621-2.cs | 3.125 | 3 | static IEnumerable<string> GetSomeData()
{
using (var connection = new SqlConnection("..."))
{
connection.Open();
using (var command = new SqlCommand("select name from some_table", connection))
using (var reader = command.ExecuteReader())
{
yield return reader.GetString(0);
}
}
}
|
b52fe2294f46b51e93d32ebd06675ba480ca6539 | C# | stoyanov7/ModPanel | /ModPanel/ModPanel/Services/UserService.cs | 2.953125 | 3 | namespace ModPanel.Services
{
using System.Collections.Generic;
using System.Linq;
using Contracts;
using Data;
using Models;
using Models.Enums;
using Models.ViewModels;
using Utilities;
public class UserService : IUserService
{
private readonly ModPanelContext context;
public UserService() => this.context = new ModPanelContext();
/// <summary>
/// Register new user in database. The first registered user become an admin.
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <param name="position"></param>
/// <returns>
/// True if the user is registered successfully.
/// False if the email is in the database.
/// </returns>
public bool Create(string email, string password, PositionType position)
{
if (this.context.Users.Any(u => u.Email == email))
{
return false;
}
var isAdmin = !this.context.Users.Any();
var passwordHash = PasswordUtilities.GetPasswordHash(password);
var user = new User
{
Email = email,
PasswordHash = passwordHash,
IsAdmin = isAdmin,
Position = position,
IsApproved = isAdmin
};
this.context.Add(user);
this.context.SaveChanges();
return true;
}
/// <summary>
/// Check if user is approved.
/// </summary>
/// <param name="email"></param>
/// <returns>True if the user is approved, otherwise false.</returns>
public bool UserIsApproved(string email)
=> this.context
.Users
.Any(u => u.Email == email && u.IsApproved);
/// <summary>
/// Check if email and password hash exist in the database.
/// </summary>
/// <param name="email"></param>
/// <param name="password"></param>
/// <returns></returns>
public bool UserExists(string email, string password)
{
var passwordHash = PasswordUtilities.GetPasswordHash(password);
return this.context
.Users
.Any(u => u.Email == email && u.PasswordHash == passwordHash);
}
public IEnumerable<AdminUsersViewModel> All()
=> this.context
.Users
.Select(u => new AdminUsersViewModel
{
Id = u.Id,
Email = u.Email,
IsApproved = u.IsApproved,
Position = u.Position,
Posts = u.Posts.Count()
})
.ToList();
public string Approve(int id)
{
var user = this.context
.Users
.Find(id);
if (user != null)
{
user.IsApproved = true;
this.context.SaveChanges();
}
return user?.Email;
}
}
} |
c276a9a32f89b23fa848f7dad6369951724d9656 | C# | sergeybykov/orleans | /Samples/1.x/Chirper/ChirperClient/ChirperClient.cs | 2.53125 | 3 | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Samples.Chirper.GrainInterfaces;
namespace Orleans.Samples.Chirper.Client
{
internal class ChirperClient : IChirperViewer
{
private IChirperViewer viewer;
private IChirperAccount publisher;
public bool IsPublisher { get; private set; }
public long UserId { get; private set; }
public bool Snapshot { get; private set; }
public async Task<bool> Run()
{
if (UserId == 0) throw new ArgumentNullException("UserId", "No user UserId provided");
Console.WriteLine("ChirperClient UserId={0}", UserId);
bool ok = true;
try
{
var config = ClientConfiguration.LocalhostSilo();
GrainClient.Initialize(config);
IChirperAccount account = GrainClient.GrainFactory.GetGrain<IChirperAccount>(UserId);
publisher = account;
List<ChirperMessage> chirps = await account.GetReceivedMessages(10);
// Process the most recent chirps received
foreach (ChirperMessage c in chirps)
{
this.NewChirpArrived(c);
}
if (Snapshot)
{
Console.WriteLine("--- Press any key to exit ---");
Console.ReadKey();
}
else
{
// ... and then subscribe to receive any new chirps
viewer = await GrainClient.GrainFactory.CreateObjectReference<IChirperViewer>(this);
if (!this.IsPublisher) Console.WriteLine("Listening for new chirps...");
await account.ViewerConnect(viewer);
// Sleeps forwever, so Ctrl-C to exit
Thread.Sleep(-1);
}
}
catch (Exception exc)
{
Console.WriteLine("Error connecting Chirper client for user={0}. Exception:{1}", UserId, exc);
ok = false;
}
return ok;
}
public Task PublishMessage(string message)
{
return publisher.PublishMessage(message);
}
#region IChirperViewer interface methods
public void NewChirpArrived(ChirperMessage chirp)
{
if (!this.IsPublisher)
{
Console.WriteLine(
@"New chirp from @{0} at {1} on {2}: {3}",
chirp.PublisherAlias,
chirp.Timestamp.ToShortTimeString(),
chirp.Timestamp.ToShortDateString(),
chirp.Message);
}
}
public void SubscriptionAdded(ChirperUserInfo following)
{
Console.WriteLine(
@"Added subscription to {0}",
following);
}
public void SubscriptionRemoved(ChirperUserInfo notFollowing)
{
Console.WriteLine(
@"Removed subscription to {0}",
notFollowing);
}
#endregion
public bool ParseArgs(string[] args)
{
IsPublisher = false;
if (args.Length <= 0) return false;
bool ok = true;
int argPos = 0;
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
if (a.StartsWith("-") || a.StartsWith("/"))
{
a = a.ToLowerInvariant().Substring(1);
switch (a)
{
case "pub":
IsPublisher = true;
break;
case "snap":
case "snapshot":
this.Snapshot = true;
break;
case "?":
case "help":
default:
ok = false;
break;
}
}
// unqualified arguments below
else if (argPos == 0)
{
long id = 0;
ok = !string.IsNullOrWhiteSpace(a) && long.TryParse(a, out id);
this.UserId = id;
argPos++;
}
else
{
Console.WriteLine("ERROR: Unknown command line argument: " + a);
ok = false;
}
if (!ok) break;
}
return ok;
}
public void PrintUsage()
{
Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Name + ".exe [/snapshot] <user ID> ");
}
}
}
|
632e567f987dd1ff71878661df623031b11e2117 | C# | ptrefall/fluid-text-adventure | /Fluid Text Adventure/Fluid Text Adventure/Items/Sword.cs | 2.875 | 3 | using System;
using System.Collections.Generic;
using FluidHTN;
using FluidHTN.Compounds;
using Fluid_Text_Adventure.Screens;
namespace Fluid_Text_Adventure
{
public class Sword : Item
{
public override string Description =>
"On the ground lies a rusty, old sword.";
public Sword(Func<AIContext, GoalState, GameScreen> SetGoal) : base(DefineDomain())
{
KeywordsToAction = new Dictionary<List<string>, Func<AIContext, GameScreen>>
{
{
new List<string> { "get", "sword" },
ctx => SetGoal?.Invoke(ctx, GoalState.GetSword)
},
{
new List<string> { "slash", "sword" },
ctx => SetGoal?.Invoke(ctx, GoalState.SlashAir)
},
{
new List<string> { "slash" },
ctx => SetGoal?.Invoke(ctx, GoalState.SlashAir)
},
{
new List<string> { "drop", "sword" },
ctx => SetGoal?.Invoke(ctx, GoalState.DropSword)
},
};
}
private static Domain<AIContext> DefineDomain()
{
var getSwordDomain = new DomainBuilder<AIContext>("Get Sword Sub-domain")
.Select("Get Sword")
.Condition("GOAL: Get Sword", (ctx => ctx.HasGoal(GoalState.GetSword)))
.Action("Get Sword")
.Condition("Has NOT Weapon", ctx => ctx.HasState(AIWorldState.HasWeapon, false))
.Do(Actions.GetSword)
.Effect("Has Weapon", EffectType.PlanAndExecute, (ctx, type) => ctx.SetState(AIWorldState.HasWeapon, true, type))
.Effect("Try Complete Goal", EffectType.PlanAndExecute, (ctx, type) => Actions.TryCompleteGoal(ctx, GoalState.GetSword, type))
.End()
.End()
.Build();
var dropSwordDomain = new DomainBuilder<AIContext>("Drop Sword Sub-domain")
.Select("Drop Sword")
.Condition("GOAL: Drop Sword", (ctx => ctx.HasGoal(GoalState.DropSword)))
.Action("Drop Sword")
.Condition("Has Weapon", ctx => ctx.HasState(AIWorldState.HasWeapon))
.Do(Actions.DropSword)
.Effect("Has NOT Weapon", EffectType.PlanAndExecute, (ctx, type) => ctx.SetState(AIWorldState.HasWeapon, false, type))
.Effect("Try Complete Goal", EffectType.PlanAndExecute, (ctx, type) => Actions.TryCompleteGoal(ctx, GoalState.DropSword, type))
.End()
.End()
.Build();
var slashAirActionDomain = new DomainBuilder<AIContext>("Slash Air Action Sub-domain")
.Action("Slash Air")
.Condition("GOAL: Slash Air", (ctx => ctx.HasGoal(GoalState.SlashAir)))
.Condition("Has Weapon", ctx => ctx.HasState(AIWorldState.HasWeapon))
.Do((ctx => Actions.Write(ctx, "You slash your sword through the air elegantly!")))
.Effect("Try Complete Goal", EffectType.PlanAndExecute, (ctx, type) => Actions.TryCompleteGoal(ctx, GoalState.SlashAir, type))
.End()
.Build();
return new DomainBuilder<AIContext>("Sword sub-domain")
.Splice(getSwordDomain)
.Splice(dropSwordDomain)
.Action("Already has sword")
.Condition("GOAL: Get Sword", (ctx => ctx.HasGoal(GoalState.GetSword)))
.Condition("Has Weapon", ctx => ctx.HasState(AIWorldState.HasWeapon))
.Do((ctx => Actions.Write(ctx, "But you're already wielding the sword!")))
.Effect("Complete Goal", EffectType.PlanAndExecute, (ctx, type) => ctx.SetGoal(GoalState.None, true, type))
.End()
.Action("Not holding sword to drop")
.Condition("GOAL: Drop Sword", (ctx => ctx.HasGoal(GoalState.DropSword)))
.Condition("Has NOT Weapon", ctx => ctx.HasState(AIWorldState.HasWeapon, false))
.Do((ctx => Actions.Write(ctx, "But you're not holding a sword!")))
.Effect("Complete Goal", EffectType.PlanAndExecute, (ctx, type) => ctx.SetGoal(GoalState.None, true, type))
.End()
.Select("Slash")
.Condition("GOAL: Slash Air", (ctx => ctx.HasGoal(GoalState.SlashAir)))
.Splice(slashAirActionDomain)
.Sequence("Pick up sword, then slash with it")
.Action("Temporary change goal")
.Effect("Get Sword Goal", EffectType.PlanOnly, (ctx, type) => Actions.ChangeGoal(ctx, type, GoalState.GetSword))
.End()
.Splice(getSwordDomain)
.Action("Temporary change goal")
.Effect("Slash Air Goal", EffectType.PlanOnly, (ctx, type) => Actions.ChangeGoal(ctx, type, GoalState.SlashAir))
.End()
.Splice(slashAirActionDomain)
.End()
.End()
.Build();
}
}
} |
47562bddd7f3dfac7247e471465f6ae4547e2143 | C# | Bunyod545/SBFramework | /src/Database/Migrator/Database/SB.Migrator.Postgres/Logics/Database/Managers/PostgresColumns/Models/PostgresColumnTypeInfo.cs | 2.84375 | 3 | using System.Collections.Generic;
using SB.Common.Helpers;
using SB.Migrator.Models.Tables.Columns;
namespace SB.Migrator.Postgres
{
/// <summary>
///
/// </summary>
public class PostgresColumnTypeInfo : ColumnTypeInfo
{
/// <summary>
///
/// </summary>
private readonly List<string> _textTypesWithLength = new List<string>()
{
"char" , "nchar", "varchar",
"nvarchar", "binary", "varbinary"
};
/// <summary>
///
/// </summary>
private readonly List<string> _numberTypesWithLength = new List<string>()
{
"decimal" , "numeric"
};
/// <summary>
///
/// </summary>
private readonly List<string> _dateTypesWithLength = new List<string>()
{
"datetime2" , "datetimeoffset", "datetimeoffset", "time"
};
/// <summary>
///
/// </summary>
public int? CharacterMaximumLenght { get; set; }
/// <summary>
///
/// </summary>
public int? CharacterOctetLenght { get; set; }
/// <summary>
///
/// </summary>
public int? NumericPrecision { get; set; }
/// <summary>
///
/// </summary>
public int? NumericPrecisionRadix { get; set; }
/// <summary>
///
/// </summary>
public int? NumericScale { get; set; }
/// <summary>
///
/// </summary>
public int? DateTimePrecision { get; set; }
/// <summary>
///
/// </summary>
/// <param name="sqlColumn"></param>
public PostgresColumnTypeInfo(PostgresColumn sqlColumn)
{
Type = sqlColumn.DataType;
CharacterMaximumLenght = sqlColumn.CharacterMaximumLenght;
CharacterOctetLenght = sqlColumn.CharacterOctetLenght;
NumericPrecision = sqlColumn.NumericPrecision;
NumericPrecisionRadix = sqlColumn.NumericPrecisionRadix;
NumericScale = sqlColumn.NumericScale;
DateTimePrecision = sqlColumn.DateTimePrecision;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string GetColumnType()
{
if (_textTypesWithLength.Contains(Type))
return GetTextWithLength();
if (_numberTypesWithLength.Contains(Type))
return GetNumberWithLength();
if (_dateTypesWithLength.Contains(Type))
return GetDateWithLength();
return base.GetColumnType();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetTextWithLength()
{
if (CharacterMaximumLenght == null)
return Type;
return GetTypeWithLength(CharacterMaximumLenght.GetValueOrDefault());
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetDateWithLength()
{
if (DateTimePrecision == null)
return Type;
return GetTypeWithLength(DateTimePrecision.GetValueOrDefault());
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetTypeWithLength(int lenght)
{
var lenghtText = lenght == -1 ? "max" : lenght.ToString();
return Type + Strings.LBracket + lenghtText + Strings.RBracket;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string GetNumberWithLength()
{
return Type + Strings.LBracket + NumericPrecision + Strings.Comma + NumericScale + Strings.RBracket;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return GetColumnType();
}
}
}
|
c817741786e5864f9dceb71a8d03913179ccfbd8 | C# | AustinRow1/Graviton_Unity_2D_Game | /Graviton/Assets/Scripts/Singletons/Light_Effects.cs | 3.109375 | 3 | /**************************************************************************************
** Filename: Light_Effects.cs
** Author: Austin Row
** Date: 8/22/16
** Description: Contains functions for handling individual light effects such
** fading, flaring, and pulsing (to be implemented in the future when
** needed).
** Functions:
** void Awake();
** void OnDestroy();
** static public Coroutine flare(Light, float);
** static public Coroutine fade_in(Light, float);
** static public Coroutine fade_out(Light, float);
** IEnumerator _flare(Light, float);
** IEnumerator _fade_in(Light, float);
** IEnumerator _fade_out(Light, float);
**************************************************************************************/
using UnityEngine;
using System.Collections;
public class Light_Effects : MonoBehaviour{
private bool is_duplicate = false; //Used to make sure instance is not set to null when a duplicate is destroyed in OnDestroy()
static public Light_Effects instance = null;
/*****************************************************************************************
* Function: void Awake()
* Description: Called at creation of script. Ensures that only one instance of this script
* can exist in the scene at any given time.
******************************************************************************************/
void Awake(){
if (instance == null)
instance = this;
else if (instance != this) {
is_duplicate = true;
Destroy (this);
}
}
/*****************************************************************************************
* Function: void OnDestroy()
* Description: Sets script instance to null when instance of script is destroyed.
******************************************************************************************/
void OnDestroy(){
if(!is_duplicate) //Ensures that instance is only set to null if there are truly no instances of this script in the scene.
instance = null;
}
/*static public void pulse(int flares){
//Does multiple flares in a row.
}*/
/*****************************************************************************************
* Function: static public Coroutine flare(Light, float)
* Description: Function for other scripts to use flare effect.
******************************************************************************************/
static public Coroutine flare(Light light, float flare_range){
return instance.StartCoroutine (instance._flare (light, flare_range));
}
/*****************************************************************************************
* Function: static public Coroutine fade_in(Light, float)
* Description: Function for other scripts to fade-in light effect.
******************************************************************************************/
static public Coroutine fade_in(Light light, float speed){
return instance.StartCoroutine (instance._fade_in (light, speed));
}
/*****************************************************************************************
* Function: static public Coroutine fade_out(Light, float)
* Description: Function for other scripts to use fade-out light effect.
******************************************************************************************/
static public Coroutine fade_out(Light light, float speed){
return instance.StartCoroutine (instance._fade_out (light, speed));
}
/*****************************************************************************************
* Function: IEnumerator _flare(Light, float)
* Description: Flares a light by rapidly increasing then decreasing the light's range.
******************************************************************************************/
IEnumerator _flare(Light light, float flare_range){
float initial_range = light.range;
float flare_speed = 20f;
while (light.range < flare_range) {
light.range += flare_speed * 1.5f * Time.deltaTime;
yield return null;
}
yield return null; //Must include this for fadeout or it will run both while loops which doesn't allow range to ever decrease.
while (light.range > initial_range) {
light.range -= flare_speed * Time.deltaTime;
yield return null;
}
}
/*****************************************************************************************
* Function: IEnumerator _fade_in(Light, float)
* Description: Brightens a single light to full brightness over time period.
******************************************************************************************/
IEnumerator _fade_in(Light light, float speed){
//If light is still fading out, put it at 0 brightness so that this light's fade out coroutine will stop
if (light.intensity != 0) {
light.intensity = 0;
yield return null;
}
while (light.intensity < 8) {
light.intensity += speed * Time.deltaTime ;
yield return null;
}
}
/*****************************************************************************************
* Function: IEnumerator _fade_out(Light, float)
* Description: Fades out a single light to 0 brightness over time period.
******************************************************************************************/
IEnumerator _fade_out(Light light, float speed){
//If light is still fading up, put it at max brightness so that this light's fade up coroutine will stop.
if (light.intensity != 8f) {
light.intensity = 8f;
yield return null;
}
while (light.intensity > 0) {
light.intensity -= speed * Time.deltaTime;
yield return null;
}
}
}
|
fd61e7b77ee05dfb040da7d4c90bd63c2b95c9d2 | C# | LisovichIvan/Crm.Sdk.Core | /Microsoft.Xrm.Sdk/Messages/CreateRequest.cs | 2.671875 | 3 | using System.Runtime.Serialization;
namespace Microsoft.Xrm.Sdk.Messages
{
/// <summary>Contains the data that is needed to create a record.</summary>
[DataContract(Namespace = "http://schemas.microsoft.com/xrm/2011/Contracts")]
public sealed class CreateRequest : OrganizationRequest
{
/// <summary>Gets or sets an instance of an entity that you can use to create a new record. Required. </summary>
/// <returns>Type: <see cref="T:Microsoft.Xrm.Sdk.Entity"></see>
/// The entity instance.</returns>
public Entity Target
{
get
{
return this.Parameters.Contains(nameof (Target)) ? (Entity) this.Parameters[nameof (Target)] : (Entity) null;
}
set
{
this.Parameters[nameof (Target)] = (object) value;
}
}
/// <summary>Initializes a new instance of the <see cref="T:Microsoft.Xrm.Sdk.Messages.CreateRequest"></see> class.</summary>
public CreateRequest()
{
this.RequestName = "Create";
this.Target = (Entity) null;
}
}
}
|
5231840ad843082a4bce9742c702925bb80e6794 | C# | mjz1211/IOT-web | /MyService/MyService/Controllers/SensorController.cs | 2.546875 | 3 | using MyService.Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Newtonsoft.Json;
namespace MyService.Controllers
{
public class SensorController : ApiController
{
//proxy 配置 device 到 sensor 最後感測資料
[HttpGet]
[HttpPost]
[RouteAttribute("cht/Sensor/sensorLastData/deviceid/{deviceid}/sensor/{sensorid}")]
public SensorData sensorLastData([FromUri]String deviceid, [FromUri]String sensorid)
{
//取得 Hosted
String hostName = Models.AppKeyUtility.getKeyValue("hosted");
String apikey = Models.AppKeyUtility.getKeyValue("apikey");
String endPoint = String.Format($"{hostName}/device/{deviceid}/sensor/{sensorid}/rawdata");
WebClient client = new WebClient();
//header CK key
client.Headers.Add("CK", apikey);
//callback delegate (事件委派)
client.DownloadStringCompleted += downloadComplete; //callback function
//client.DownloadStringAsync(new Uri(endPoint));
//String result = await client.DownloadStringTaskAsync(endPoint);
String result = client.DownloadString(endPoint);
//JObject obj = Newtonsoft.Json.JsonConvert.DeserializeObject(result) as JObject;
//result = obj.GetValue("time").ToString();
//JToken jt = obj.GetValue("value"); //不是字串也不是一個整數[....] Json Array
//result = jt[0].ToString(); //jt[indexer] 內建集合物件 使用索引子語法[]--特殊類型屬性
SensorData data = JsonConvert.DeserializeObject(result, typeof(SensorData))
as SensorData;
return data;
}
//事件程序
private void downloadComplete(object sender, DownloadStringCompletedEventArgs e)
{
String jsonString = e.Result;
System.Console.WriteLine("This is callback");
}
}
}
|