Discord.NET Users playing the same game - c#

I am trying to create a command that returns the number of guild members that are currently playing a specified game.
Example (! is my prefix): !playing League of Legends.
If there are 5 members playing League of Legends, output:
There are 5 users currently playing League of Legends.
I set up the following, from debugging I was able to pick up that v.Game.toString() returns the correct string but for some reason the if statement does not trigger. It also catches an exception that is thrown whenever members are not playing a game (I assumed it's null?), is there a workaround for that? Why does this not count how many members are playing a certain game?
[Command("playing")]
public async Task playingGame(params string[] s)
{
string gameName = "";
int count = 0;
for (int i = 0; i < s.Length; i++)
{
gameName += s[i] + " ";
}
await Context.Channel.SendMessageAsync("Looking for: " + gameName);
var u = Context.Guild.Users;
foreach (var v in u)
{
await Context.Channel.SendMessageAsync("v = " + v.ToString());
try
{
await Context.Channel.SendMessageAsync(v.Game.ToString());
if (v.Game.ToString().ToLower().Equals(gameName.ToLower()))
{
count++;
await Context.Channel.SendMessageAsync("Found match, count = " + count);
}
}
catch (Exception x)
{
await Context.Channel.SendMessageAsync("Exception throw caught");
}
}
if (count > 1) {
await Context.Channel.SendMessageAsync("There are " + count + " users currently playing " + gameName + ".");
}
else if (count == 1)
{
await Context.Channel.SendMessageAsync("There is " + count + " user currently playing " + gameName + ".");
}
else if (count == 0)
{
await Context.Channel.SendMessageAsync("No one is currently playing " + gameName + ".");
}
}
This is the exception:
System.ArgumentException: Argument cannot be blank
Parameter name: Content
at Discord.Preconditions.NotNullOrEmpty(String obj, String name, String msg)
at Discord.API.DiscordRestApiClient.<CreateMessageAsync>d__77.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
Pic of where if statement should trigger (username blocked for privacy reasons):

There is no need to have params string[] s for the game parameter. Just use the Remainder attribute.
I have also simplified this code alot :
[Command("playing")]
public async Task GetUsersPlaying([Remainder]string game)
{
await Context.Message.DeleteAsync();
var users = Context.Guild.Users.Where(x => x.Game.ToString() == game).Distinct().Select(x => x.Username);
var count = users.Count();
var SeparatedList = string.Join(", ", users);
string message;
if (count > 1)
message = $"There are {count} users playing {game}. [{SeparatedList}]";
else if (count == 1)
message = $"There is {count} user playing {game}. [{SeparatedList}]";
else
message = $"There is no one playing {game}.";
await Context.Channel.SendMessageAsync(message);
}

Related

How to get global balance for Biannce.NET

At the moment i can just get the SPOT balance with this lines:
var subAccountBalances = await binanceClient.SpotApi.Account.GetBalancesAsync();
decimal total = 0;
if(subAccountBalances.Success)
{
foreach (var item in subAccountBalances.Data)
{
Debug.WriteLine(item.Asset + " : " + item.Total + " BTC: " + item.BtcValuation);
total += item.BtcValuation;
}
}
else
{
Debug.WriteLine(subAccountBalances.Error);
}
Debug.WriteLine("Total in BTC: " + total);
And this gives me my SPOT balance.
Is there a way to get all the balances togeather (futures, margin, earn, etc...)
and get each item individualy?
Im using:
using Binance.Net;
using Binance.Net.Clients;
using Binance.Net.Objects;
Thanks for the help!
I have tried this functions, but non of them gives me the full global balance:
await binanceClient.SpotApi.Account.GetBalancesAsync();
await binanceClient.SpotApi.CommonSpotClient.GetBalancesAsync();
await binanceClient.SpotApi.Account.GetAccountInfoAsync();

Waiting for web call to finish before continuing code in Unity3d

I've read many articles but I don't seem to get it. I have this code working now because I hardcode a 3 second delay so there is enough time for the web call to finish so when the score is displayed there is data. But what I really want is to have the web call finish and THEN display the score. Help ?
IEnumerator Start()
{
client = new MobileServiceClient(_appUrl, _appKey);
table = client.GetTable<Highscore>("Highscores");
yield return StartCoroutine(ReadItems());
DisplayScores();
}
void Update()
{
}
public void btn_GoBack()
{
Application.LoadLevel("StartScene");
}
private void OnReadItemsCompleted(IRestResponse<List<Highscore>> response)
{
if (response.StatusCode == HttpStatusCode.OK)
{
Debug.Log("OnReadItemsCompleted data: " + response.Content);
List<Highscore> items = response.Data;
Debug.Log("Read items count: " + items.Count);
Scores = items;
}
else
{
Debug.Log("Error Status:" + response.StatusCode + " Uri: " + response.ResponseUri);
}
}
private IEnumerator ReadItems()
{
table.Read<Highscore>(OnReadItemsCompleted);
yield return new WaitForSeconds(3);
}
private void DisplayScores()
{
txtHighScores.text = "";
int numberOfScores = Math.Min(Scores.Count, 5);
for (int i = 0; i < numberOfScores; i++)
{
string name = Scores[i].username.ToString();
string score = Scores[i].score.ToString();
txtHighScores.text += (i + 1).ToString() + ". " +
" - " + name + "\r\n" +
score.ToString().PadLeft(4, '0');
}
}
It is important to pass a parameter with Startcorutine method,
Otherwise it gives error.
So try my fix in your code.
IEnumerator Start()
{
client = new MobileServiceClient(_appUrl, _appKey);
table = client.GetTable<Highscore>("Highscores");
yield return StartCoroutine(ReadItems(2.0f)); //delay
DisplayScores();
}
IEnumerator ReadItems(float delay)
{
yield return new WaitForSeconds(delay);
table.Read<Highscore>(OnReadItemsCompleted);
}
Remove the method call for "DisplayScores()" from Start()
And insert DisplayScores() as the last line of method callback OnReadItemsCompleted
And then you should remove the line yield return new WaitForSeconds(3);

Loading multiple files Exception error C#

I am making the game minesweeper and I am trying to implement a highScores feature. I am trying to load 3 different files (each one holds the high scores for each of the 3 difficulty settings) into 3 different richTextBox's. When I run the app and click the 'high scores' tab from the menu strip it works the first time. However if I play a game and then try to access the high scores form I get an Exception error -
An unhandled exception of type 'System.IO.IOException' occurred in
mscorlib.dll
Additional information: The process cannot access the file
'C:\Users\jzcon_000\Copy\Visual
Studio\Projects\Assignment1\Assignment1\bin\Debug\highScoresMed.txt'
because it is being used by another process
This is where the call is made
private void highScoresToolStripMenuItem_Click(object sender, EventArgs e)
{
Minesweeper.HighSc highScore = new Minesweeper.HighSc();
highScore.read();
highScore.Show();
}
This is the method in my HighSc class
public void read()
{
StreamReader readerE = File.OpenText("highScoresEasy.txt");
StreamReader readerM = File.OpenText("highScoresMed.txt");
StreamReader readerH = File.OpenText("highScoresHard.txt");
if (readerE != null)
{
string readEasy = File.ReadAllText("highScoresEasy.txt");
richTextBox1.Text = readEasy;
}
readerE.Close();
if (readerM != null)
{
string readMed = File.ReadAllText("highScoresMed.txt");
richTextBox2.Text = readMed;
}
readerM.Close();
if (readerH != null)
{
string readHard = File.ReadAllText("highScoresHard.txt");
richTextBox3.Text = readHard;
}
readerH.Close();
}
Heres the save high scores class
namespace Minesweeper
{
class Save
{
int diff, hr, min, sec;
string player;
public Save(int difficulty, int hour, int minute, int second, string playerN)
{
diff = difficulty;
hr = hour;
min = minute;
sec = second;
player = playerN;
}
public void save()
{
StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true);
StreamWriter writerMed = new StreamWriter("highScoresMed.txt", true);
StreamWriter writerHard = new StreamWriter("highScoresHard.txt", true);
if (diff == 1)
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerEasy.Close();
}
else if (diff == 2)
{
writerMed.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerMed.Close();
}
else if (diff == 3)
{
writerHard.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
writerHard.Close();
}
}
}
}
So when you have the difficulty level set to 1 and then save, you open the StreamWriters for both the level2 and level3 but never close them.
This could only mean that when you try to load the highscore for these two levels you will find your files locked by your previous save.
You should change your Save method to open only the required file
public void save()
{
if (diff == 1)
{
using(StreamWriter writerEasy = new StreamWriter("highScoresEasy.txt", true))
{
writerEasy.WriteLine("Time: " + hr + ":" + min + ":" + sec + " " + "Name: " + player);
}
}
else if (diff == 2)
....
else if (diff == 3)
....
I suggest also to use the using statement in your reading method to be sure that also in case of exceptions the stream are correctly disposed

Null Refrence Exception Unhandled in my Microprocessor simulator [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
So I have my memory class which looks like this:
namespace GeminiCore
{
public class Memory
{
public static int[] memory = new int[256];
public string nextInstruction;
public static int cacheSize = 8;
public CPU myCPU;
public struct frame
{
public bool dirtyBit;
public int isEmpty;
public int value;
public int tag;
public frame(int cacheSize)
{
dirtyBit = false;
isEmpty = 1;
value = 0;
tag = 0;
}
}
public int solveMemory(int value, int instr, frame[] myCache)
{
Console.WriteLine("I reached the solveMemory!!!");
int block = value % cacheSize;
if(instr == 127 || instr == 125 || instr == 124 || instr == 123
|| instr == 122 || instr == 121|| instr == 120)
{
Console.WriteLine("I reached the read section!!!");
if(myCache[block].isEmpty == 0) //Read hit
if(myCache[block].tag == value)
return myCache[block].value;
else
{
myCache[block].value = memory[value]; //Read Miss
myCache[block].tag = value;
myCache[block].isEmpty = 0;
Console.WriteLine("Read Miss --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
return myCache[block].value;
}
}
else
{
Console.WriteLine("I reached the write section!!!");
if (myCache[block].isEmpty == 1) //Write Miss
{
Console.WriteLine("Write Miss --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
memory[value] = myCPU.ACC;
}
else
{
if (myCache[block].dirtyBit == false)
{
if (myCache[block].tag != value)
{
myCache[block].value = myCPU.ACC; //Write Hit
myCache[block].dirtyBit = true;
myCache[block].tag = value;
Console.WriteLine("Write Hit --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
}
}
else
{
memory[myCache[block].tag] = myCache[block].value;
myCache[block].value = myCPU.ACC;
myCache[block].tag = value;
myCache[block].dirtyBit = false;
Console.WriteLine("Write Hit --- The Cache is as follows: block = " + block + " the value at this block is: " + myCache[block].value + " the tag at this block is: " + myCache[block].tag);
}
}
}
return value;
}
}
}
and then I have my CPU class, and I will just post a small snippet of where the error is occurring:
public Memory myMemory;
public static Memory.frame[] myCache = new Memory.frame[Memory.cacheSize];
public void doInstruction()
{
var instr = (finalCodes[i] >> 9) & 127; //Parses op code to find instruction
var immed = (finalCodes[i] >> 8) & 1; //Parses op code to find immediate value
var value = (finalCodes[i] & 255); //Parse op code to find value
foreach (Memory.frame x in myCache)
{
Console.WriteLine("Dirtybit: " + x.dirtyBit + " isEmpty: " + x.isEmpty + " tag: " + x.tag + " value: " + x.value);
}
switch (instr)
{
case (127): //LDA instruction
if (immed == 1)
ACC = value;
else if (immed == 0)
//ACC = Memory.memory[value];
ACC = myMemory.solveMemory(value, instr, myCache);
break;
case (126): //STA instruction
if (immed == 0)
{
Console.WriteLine("The value is: " + value + " The instruction is: " + instr);
foreach (Memory.frame x in myCache)
{
Console.WriteLine("Dirtybit: " + x.dirtyBit + " isEmpty: " + x.isEmpty + " tag: " + x.tag + " value: " + x.value);
}
//Memory.memory[value] = ACC;
myMemory.solveMemory(value, instr, myCache);
}
So here is my problem, when I run my test which takes in assembly code and translates it to binary then runs through the code, when I get to the second command "sta" it should go to the line:
myMemory.solveMemory(value, instr, myCache);
It then gives me a Null Reference Exception when it reaches that point. As you can see I have some command line output to try and see where it is going. It prints out the contents of myCache right before that line. It does not reach any of the debug statements in the solveMemory function however, not even the first one that says:
Console.WriteLine("I reached the solveMemory!!!");
I'm not really sure what is causing this error and I've been looking at it for quite some time. Hopefully one of you will be able to find where exactly I am messing up. Thanks for the time.
public Memory myMemory;
should be:
public Memory myMemory = new Memory();

How to display opening times?

I'm trying to show intervals of working hours/days it's should look like this:
(source: clip2net.com)
I have table where I'm storing day number, open time and closing time for each day
(source: clip2net.com)
Then I created query=>
var groups = from s in this.OpenTimes
orderby s.Day
group s by new { s.Till, s.Start } into gr
select new
{
Time = gr.Key.Start + "-" + gr.Key.Till,
Days = this.OpenTimes
.Where(o => o.Start == gr.Key.Start && o.Till == gr.Key.Till)
.OrderBy(d => d.Day).Select(d => d.Day).ToArray()
};
This query provides all grouped time intervals and days that included to this time-range
But I faced with problem - I created second half that representing this groups, but it's not working properly.
Maybe somebody could explain to me needed point of vision or this basic logic of showing opening times.
Thanks in advice...
Next approach works for me:
result screen
public string OpeningTimesString
{
get
{
if (!this.OpeningTimes.IsLoaded)
this.OpeningTimes.Load();
var groups = (from s in this.OpeningTimes
orderby s.Day, s.Start, s.Stop
group s by new { Stop = formatTime(s.Stop), Start = formatTime(s.Start), s.Day } into gr
select new
{
Time = gr.Key.Start + "-" + gr.Key.Stop,
Day = gr.Key.Day
}).ToList();
string result = "";
int tmp = 1;
for (int i = 0; i < groups.Count(); i++)
{
//One one = new One();
bool exit = false;
tmp = i;
while (exit == false)
{
if (i + 1 < groups.Count && groups[i].Time.Equals(groups[i + 1].Time))
{
i++;
}
else
{
if (tmp != i)
result += (NormalDayOfWeek)(groups[tmp].Day - 1) + "-" + (NormalDayOfWeek)(groups[i].Day - 1) + " : " + groups[i].Time + "<br />";
else
result += (NormalDayOfWeek)(groups[i].Day - 1) + " : " + groups[i].Time + "<br />";
exit = true;
}
}
}
if (result.IsNotNull())
return result;
else
return "[%Not yet defined]";
}
}

Categories