Repost: Discord.py & Sympy(mostly discord.py I think) - discord.py

I'm trying to make a math discord bot.
I am pretty sure that my Sympy code is correct and it is just discord.py being funky.
Code:
#client.command()
async def solve(ctx, equation):
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
equation = equation.split("=")
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
await ctx.send(f"```{solve(eqn)}```")
Please assume that I have all imports necessary.
I am getting this error:
Ignoring exception in command solve:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "math.py", line 42, in solve
eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 1008, in parse_expr
return eval_expr(code, local_dict, global_dict)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\sympy\parsing\sympy_parser.py", line 902, in eval_expr
expr = eval(
File "<string>", line 1
Integer (2 )+Integer (3 )Symbol ('x' )
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\justi_zts5a0w\PycharmProjects\discord.py\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: SyntaxError: invalid syntax (<string>, line 1)

Judging from the error you are getting, the problem is not from discord.py, it comes from sympy. And judging at the output of the code it has to do with the way you are introducing the parameter equation.
I did the following calls in SymPy Live and it outputted well:
>>> from sympy.parsing.sympy_parser import parse_expr
>>> equation = 'x+1 = 0'
>>> equation = equation.split('=')
>>> eqn = Eq(parse_expr(equation[0]), parse_expr(equation[1]))
>>> print(eqn)
Eq(x + 1, 0)
In your code, however, it is telling you that the parse_expr cannot evaluate the expression correctly due to the syntax being introduced. Make sure your input equation has a valid format.

Related

Problem with debugging TorchScript RuntimeError: Dimension out of range

I've created a simple NLP model in PyTorch, trained it and it works as expected in Python.
Then I've exported it to the TorchScript with jit.trace. And loading it back into Python works fine and model works as expected.
But when I try to execute it in rust with tch-rs (Rust bindings for the C++ api of PyTorch), the following error occurs and I have no idea how to debug it:
Error: Torch("The following operation failed in the TorchScript interpreter.
Traceback of TorchScript, serialized code (most recent call last):
File \"code/__torch__/___torch_mangle_469.py\", line 17, in forward
dropout = self.dropout
bert = self.bert
_0 = (dropout).forward((bert).forward(input_id, mask, ), )
~~~~~~~~~~~~~ <--- HERE
_1 = (relu).forward((linear).forward(_0, ), )
return _1
File \"code/__torch__/transformers/models/bert/modeling_bert/___torch_mangle_465.py\", line 19, in forward
batch_size = ops.prim.NumToTensor(torch.size(input_id, 0))
_0 = int(batch_size)
seq_length = ops.prim.NumToTensor(torch.size(input_id, 1))
~~~~~~~~~~ <--- HERE
_1 = int(seq_length)
_2 = int(seq_length)
Traceback of TorchScript, original code (most recent call last):
/user/.conda/envs/tch/lib/python3.10/site-packages/transformers/models/bert/modeling_bert.py(954): forward
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/nn/modules/module.py(1176): _slow_forward
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/nn/modules/module.py(1192): _call_impl
/var/folders/zs/vmmy3w4n0ns1c0kj91skmfnm0000gn/T/ipykernel_10987/868892765.py(17): forward
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/nn/modules/module.py(1176): _slow_forward
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/nn/modules/module.py(1192): _call_impl
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/jit/_trace.py(957): trace_module
/user/.conda/envs/tch/lib/python3.10/site-packages/torch/jit/_trace.py(753): trace
/var/folders/zs/vmmy3w4n0ns1c0kj91skmfnm0000gn/T/ipykernel_10987/749605851.py(1): <module>
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/interactiveshell.py(3430): run_code
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/interactiveshell.py(3341): run_ast_nodes
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/interactiveshell.py(3168): run_cell_async
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/async_helpers.py(129): _pseudo_sync_runner
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/interactiveshell.py(2970): _run_cell
/user/.conda/envs/tch/lib/python3.10/site-packages/IPython/core/interactiveshell.py(2941): run_cell
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/zmqshell.py(531): run_cell
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/ipkernel.py(380): do_execute
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/kernelbase.py(700): execute_request
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/kernelbase.py(383): dispatch_shell
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/kernelbase.py(496): process_one
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/kernelbase.py(510): dispatch_queue
/user/.conda/envs/tch/lib/python3.10/asyncio/events.py(80): _run
/user/.conda/envs/tch/lib/python3.10/asyncio/base_events.py(1868): _run_once
/user/.conda/envs/tch/lib/python3.10/asyncio/base_events.py(597): run_forever
/user/.conda/envs/tch/lib/python3.10/site-packages/tornado/platform/asyncio.py(212): start
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel/kernelapp.py(701): start
/user/.conda/envs/tch/lib/python3.10/site-packages/traitlets/config/application.py(990): launch_instance
/user/.conda/envs/tch/lib/python3.10/site-packages/ipykernel_launcher.py(12): <module>
/user/.conda/envs/tch/lib/python3.10/runpy.py(75): _run_code
/user/.conda/envs/tch/lib/python3.10/runpy.py(191): _run_module_as_main
RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
")
And here is the simple model that I try to execute:
from torch import nn
from transformers import BertModel
class BertClassifier(nn.Module):
def __init__(self, dropout=0.5):
super(BertClassifier, self).__init__()
self.bert = BertModel.from_pretrained('bert-base-cased')
self.dropout = nn.Dropout(dropout)
self.linear = nn.Linear(768, 5)
self.relu = nn.ReLU()
def forward(self, input_id, mask):
_, pooled_output = self.bert(input_ids= input_id, attention_mask=mask,return_dict=False)
dropout_output = self.dropout(pooled_output)
linear_output = self.linear(dropout_output)
final_layer = self.relu(linear_output)
return final_layer
I'm new to ML and I can't find any docs on how to debug TorchScript runtime errors so I appreciate any help in solving this problem

Discord.py error: "ValueError: <class 'str'> is not a valid ChannelType"

I don't understand what the error is.
> Ignoring exception in command weather:
> Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/enums.py", line 168, in __call__
> return cls._enum_value_map_[value]
> KeyError: <class 'str'>
> During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "/home/timoha/discord_bot/main.py", line 166, in weather
async with discord.channel.ChannelType(value=str):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/enums.py", line 170, in __call__
> raise ValueError(f"{value!r} is not a valid {cls.__name__}")
> ValueError: <class 'str'> is not a valid ChannelType
>
> The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
> raise ApplicationCommandInvokeError(exc) from exc
> discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: <class 'str'> is not a valid ChannelType
Code:
#bot.slash_command(name="weather", description="Погода")
async def weather(ctx, *, city: str):
city_name = city
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
channel = ctx.message
if x["cod"] != "404":
async with discord.channel.ChannelType(value=str):
value=str
y = x["главный"]
current_temperature = y["температура"]
current_temperature_celsiuis =str(round(current_temperature - 273.15))
current_pressure = y["давление"]
current_humidity = y["влажность"]
z = x["погода"]
weather_description = z[0]["описание"]
weather_description = z[0]["описание"]
embed = discord.Embed(title=f"Погода в {city_name}",
color=ctx.guild.me.top_role.color,
timestamp=ctx.message.created_at,)
embed.add_field(name="Описание", value=f"**{weather_description}**", inline=False)
embed.add_field(name="Температура(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
embed.add_field(name="Влажность(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
embed.set_footer(text=f"Запрошенный {ctx.author.name}")
await channel.send(embed=embed)
else:
await channel.send("Город не найден.")
I tried to change a lot of things, but I still can't figure out what the problem is.
There's a few issues with your code - that error is probably just the first one. I've attempted to rewrite what you've provided with some explanation but hopefully it replicates what you're trying to do.
#bot.slash_command(name="weather", description="Погода")
async def weather(ctx, *, city: str):
# as we're doing an API call here - let's defer so the interaction doesn't timeout
await ctx.defer()
# no reason to redefine another variable called 'city_name' equal to 'city' - just use 'city' everywhere
# could also use a f-string for creating the URL here
# complete_url = f"{base_url}appid={api_key}&q={city}"
complete_url = base_url + "appid=" + api_key + "&q=" + city
response = requests.get(complete_url)
json_response = response.json()
if json_response["cod"] == "404":
# if it's 404, let's send the error message and return early
# means we don't have a big nested "if" block
await channel.send("Город не найден.")
return
y = json_response["главный"]
z = json_response["погода"]
current_temperature = y["температура"]
current_temperature_celsiuis =str(round(current_temperature - 273.15))
current_pressure = y["давление"]
current_humidity = y["влажность"]
weather_description = z[0]["описание"]
weather_description = z[0]["описание"]
# create the embed
embed = discord.Embed(
title=f"Погода в {city}",
color=ctx.guild.me.top_role.color,
timestamp=ctx.message.created_at
)
embed.add_field(name="Описание", value=f"**{weather_description}**", inline=False)
embed.add_field(name="Температура(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
embed.add_field(name="Влажность(%)", value=f"**{current_humidity}%**", inline=False)
embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
embed.set_footer(text=f"Запрошенный {ctx.author.name}")
# now let's send our response
# ctx.send will send to the channel that the user used the slash command in
await ctx.send(embed=embed)
The ctx variable docs.
What I changed:
removed creating a variable called city_name that was exactly equal to city - seemed redundant
added ctx.defer() - if our code takes a little while it's good to defer so the interaction doesn't timeout
removed channel = ctx.message. We can get the channel later if we need to (we don't in this case) but this was setting it equal to the message that invoked the application command (which isn't really a message) so we aren't accomplishing anything here anyways
if we get a 404 response; send error message and return. Better to do this than have a big nested if block in my opinion.
I also renamed x to json_response as I prefer descriptive variable names but I gave up on y and z.
got rid of the whatever the async with statement was trying to accomplish
used ctx.send(embed=embed) at the bottom to send your created embed to the channel that the user used the application command in
Hopefully, this is what you want it to do and hopefully you understand what's going on a bit now. It might be worth having a look through some of the examples and documentation to get a better grasp on how it all works.
Another change you could make, is swapping out requests for aiohttp-requests to make non-blocking API calls.
I took advantage of your help, and I am grateful to you in many ways, but I am just starting my way in programming and learning from a real example. So I corrected my code to yours and I was given a new set of errors, which I also can't figure out a little.
gnoring exception in command weather: Traceback (most recent call
last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs) File
"/home/timoha/discord_bot/main.py", line 162, in weather
y = json_response["главный"] KeyError: 'главный'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/timoha/discord_bot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command
raised an exception: KeyError: 'главный'

IllegalArgumentException on any functions with GeoDataFrame

I'm trying to do anything with my GeoDataFrame that I'm importing from the Census website, but when I try to dissolve or overlay with other data frames I get:
pygeos.GEOSException: IllegalArgumentException: Argument must be Polygonal or LinearRing
It won't every overlay itself which is weird. I've exploded it to get rid of the multi polygon and buffered the three invalid polygons, but I'm lost. New to geopandas but I can general feel my way around these things. Any help would be appreciated.
Is my installed package the issue?
Download this file
>>> import geopandas as gpd
>>> SHAPE_URL = 'https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_cd116_20m.zip'
>>> cd = gpd.read_file(SHAPE_URL)
>>> cd.dissolve()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1538, in dissolve
g = self.groupby(group_keys=False, **groupby_kwargs)[self.geometry.name].agg(
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/generic.py", line 259, in aggregate
return self._python_agg_general(func, *args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1173, in _python_agg_general
result, counts = self.grouper.agg_series(obj, f)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/ops.py", line 691, in agg_series
return self._aggregate_series_pure_python(obj, func)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/ops.py", line 741, in _aggregate_series_pure_python
res = func(group)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pandas/core/groupby/groupby.py", line 1160, in <lambda>
f = lambda x: func(x, *args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/geodataframe.py", line 1535, in merge_geometries
merged_geom = block.unary_union
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/base.py", line 728, in unary_union
return self.geometry.values.unary_union()
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/array.py", line 652, in unary_union
return vectorized.unary_union(self.data)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/geopandas/_vectorized.py", line 892, in unary_union
return _pygeos_to_shapely(pygeos.union_all(data))
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pygeos/decorators.py", line 80, in wrapped
return func(*args, **kwargs)
File "/Users/joefedorowicz/Development/virtualenvs/briefcase/lib/python3.9/site-packages/pygeos/set_operations.py", line 388, in union_all
result = lib.unary_union(collections, **kwargs)
pygeos.GEOSException: IllegalArgumentException: Argument must be Polygonal or LinearRing

How come I can't use message.user.tag?

I'm trying to get the 4-digit tag of the person who used the command !hours, but discord won't recognize user.tag
import discord
from discord import message
from discord.ext import commands
client = commands.Bot(command_prefix = '!')
##########HOURS##########
chung_victor = [21, 10]
##########HOURS##########
# chung_victor
if usertag == 5308:
h = chung_victor[0]
m = chung_victor[1]
await ctx.send(f'> You currently have {h} hours and {m} minutes!')
And when I use !hours, I get the error message
Ignoring exception in command hours:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 36, in hours
usertag = message.user.tag
AttributeError: module 'discord.message' has no attribute 'user'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.message' has no attribute 'user'
Well, as you see to get user name you need to use it as user.name and same goes for the discriminator user.discriminator. You can refer to the code below :
#bot.command()
async def test(ctx, member : discord.Member, *,reason = None) :
user = member.discriminator
await ctx.send(f" User Tag is : {user} ")
In the example above, I set a command test and user must tag someone after a command like:
!test #Victor Chung and ! is a command_prefix.
Thank You :)

asyncio_redis and aioredis error on getting a list of keys

When I try to get values for a list of keys using asyncio_redis or aioredis, I am getting the following error. I know it is about something python socket, but unable to resolve the error. I attached both the code and error log with this issue. Here keys are a list of large byte arrays. get_params_redis is called by multiple processes. Any help would be appreciated, thanks!
async def multi_get_key_redis(keys):
redis = await aioredis.create_redis_pool(
'redis://localhost')
result =[]
for key in keys:
result.append(await redis.get(key))
# assert result == await asyncio.gather(*keys)
# return result
redis.close()
await redis.wait_closed()
print(result)
return result
def get_params_redis(shapes):
i = -1
params=[]
keys = []
for s in range(len(shapes)):
keys.append(s)
values = asyncio.get_event_loop().run_until_complete(multi_get_key_redis(keys))
for shape in shapes:
i = i + 1
param_np = pc._loads(values[i]).reshape(shape)
param_tensor = torch.nn.Parameter(torch.from_numpy(param_np))
params.append(param_tensor)
return params
Error Log:
Process Process-1:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 258, in _bootstrap
self.run()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/process.py", line 93, in run
self._target(*self._args, **self._kwargs)
File "/Users/srujithpoondla/largescaleml_project/train_redis.py", line 33, in train_redis
train_redis_epoch(epoch, args, model, train_loader, optimizer,shapes_len, loop)
File "/Users/srujithpoondla/largescaleml_project/train_redis.py", line 43, in train_redis_epoch
params = get_params_redis(shapes_len,loop)
File "/Users/srujithpoondla/largescaleml_project/common_functions.py", line 76, in get_params_redis
params = loop.run_until_complete(multi_get_key_redis(keys))
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 454, in run_until_complete
self.run_forever()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 421, in run_forever
self._run_once()
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 1395, in _run_once
event_list = self._selector.select(timeout)
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/selectors.py", line 577, in select
kev_list = self._kqueue.control(None, max_ev, timeout)
OSError: [Errno 9] Bad file descriptor

Resources