Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert string with anomalous backslash into a raw string #225

Merged
merged 2 commits into from
Oct 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 35 additions & 13 deletions minato_namikaze/bot_files/lib/classes/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
import discord
from discord.ext import commands

time_regex = re.compile("(?:(\d{1,5})(h|s|m|d))+?")
time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")

time_dict = {"h": 3600, "s": 1, "m": 60, "d": 86400}


class TimeConverter(commands.Converter):
async def convert(self, ctx, argument):
args = argument.lower()
Expand All @@ -24,15 +25,19 @@ async def convert(self, ctx, argument):
raise commands.BadArgument(f"{key} is not a number!")
return round(time)


class Arguments(argparse.ArgumentParser):
def error(self, message):
raise RuntimeError(message)


def can_execute_action(ctx, user, target):
return user.id == ctx.bot.owner_id or \
user == ctx.guild.owner or \
user.top_role > target.top_role
return (
user.id == ctx.bot.owner_id
or user == ctx.guild.owner
or user.top_role > target.top_role
)


class MemberID(commands.Converter):
async def convert(self, ctx, argument):
Expand All @@ -42,44 +47,61 @@ async def convert(self, ctx, argument):
try:
member_id = int(argument, base=10)
except ValueError:
raise commands.BadArgument(f"{argument} is not a valid member or member ID.") from None
raise commands.BadArgument(
f"{argument} is not a valid member or member ID."
) from None
else:
m = await ctx.bot.get_or_fetch_member(ctx.guild, member_id)
if m is None:
# hackban case
return type('_Hackban', (), {'id': member_id, '__str__': lambda s: f'Member ID {s.id}'})()
return type(
"_Hackban",
(),
{"id": member_id, "__str__": lambda s: f"Member ID {s.id}"},
)()

if not can_execute_action(ctx, ctx.author, m):
raise commands.BadArgument('You cannot do this action on this user due to role hierarchy.')
raise commands.BadArgument(
"You cannot do this action on this user due to role hierarchy."
)
return m


class BannedMember(commands.Converter):
async def convert(self, ctx, argument):
if argument.isdigit():
member_id = int(argument, base=10)
try:
return await ctx.guild.fetch_ban(discord.Object(id=member_id))
except discord.NotFound:
raise commands.BadArgument('This member has not been banned before.') from None
raise commands.BadArgument(
"This member has not been banned before."
) from None

ban_list = await ctx.guild.bans()
entity = discord.utils.find(lambda u: str(u.user) == argument, ban_list)
entity = discord.utils.find(
lambda u: str(u.user) == argument, ban_list)

if entity is None:
raise commands.BadArgument('This member has not been banned before.')
raise commands.BadArgument(
"This member has not been banned before.")
return entity


class ActionReason(commands.Converter):
async def convert(self, ctx, argument):
ret = f'{ctx.author} (ID: {ctx.author.id}): {argument}'
ret = f"{ctx.author} (ID: {ctx.author.id}): {argument}"

if len(ret) > 512:
reason_max = 512 - len(ret) + len(argument)
raise commands.BadArgument(f'Reason is too long ({len(argument)}/{reason_max})')
raise commands.BadArgument(
f"Reason is too long ({len(argument)}/{reason_max})"
)
return ret


def safe_reason_append(base, to_append):
appended = base + f'({to_append})'
appended = base + f"({to_append})"
if len(appended) > 512:
return base
return appended
13 changes: 6 additions & 7 deletions minato_namikaze/bot_files/lib/mendeleev/electronegativity.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
# Code written here is not mine.
# Its taken from https://github.com/lmmentel/mendeleev

"""
Electronegativity scale formulas
"""
Expand Down Expand Up @@ -69,7 +68,7 @@ def li_xue(ionization_energy: float, radius: float, valence_pqn: int) -> float:


def martynov_batsanov(ionization_energies: List[float]) -> float:
"""
r"""
Calculates the electronegativity value according to Martynov and
Batsanov as the average of the ionization energies of the valence
electrons
Expand All @@ -82,7 +81,7 @@ def martynov_batsanov(ionization_energies: List[float]) -> float:
- :math:`I_{k}` is the :math:`k` th ionization potential.
"""

return math.sqrt(abs(sum(ionization_energies)/len(ionization_energies)))
return math.sqrt(abs(sum(ionization_energies) / len(ionization_energies)))


def mulliken(
Expand All @@ -91,7 +90,7 @@ def mulliken(
missing_is_zero: bool = False,
allow_negative_ea: bool = False,
) -> float:
"""
r"""
Return the absolute electronegativity (Mulliken scale), calculated as
Args:
ionization_energy: ionization energy
Expand Down Expand Up @@ -131,7 +130,7 @@ def nagle(nvalence: int, polarizability: float) -> float:


def sanderson(radius: float, noble_gas_radius: float) -> float:
"""
r"""
Calculate Sanderson's electronegativity
Args:
radius: radius value for the element
Expand All @@ -145,7 +144,7 @@ def sanderson(radius: float, noble_gas_radius: float) -> float:


def generic(zeff: float, radius: float, rpow: float = 1, apow: float = 1) -> float:
"""
r"""
Calculate the electronegativity from a general formula
Args:
zeff: effective nuclear charge
Expand All @@ -160,4 +159,4 @@ def generic(zeff: float, radius: float, rpow: float = 1, apow: float = 1) -> flo
- :math:`\\alpha,\\beta` parameters
"""

return math.pow(zeff / math.pow(radius, rpow), apow)
return math.pow(zeff / math.pow(radius, rpow), apow)
10 changes: 6 additions & 4 deletions minato_namikaze/bot_files/lib/mendeleev/mendeleev.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ def element(ids: Union[int, str]) -> Element:
return _get_element(ids)
else:
raise ValueError(
"Expected a <list>, <tuple>, <str> or <int>, got: {0:s}".format(type(ids))
"Expected a <list>, <tuple>, <str> or <int>, got: {0:s}".format(
type(ids))
)


Expand All @@ -72,7 +73,8 @@ def _get_element(ids):
elif isinstance(ids, int):
return session.query(Element).filter(Element.atomic_number == ids).one()
else:
raise ValueError("Expecting a <str> or <int>, got: {0:s}".format(type(ids)))
raise ValueError(
"Expecting a <str> or <int>, got: {0:s}".format(type(ids)))


def get_all_elements():
Expand Down Expand Up @@ -106,7 +108,7 @@ def ids_to_attr(ids, attr="atomic_number"):


def deltaN(id1, id2, charge1=0, charge2=0, missingIsZero=True):
"""
r"""
Calculate the approximate fraction of transferred electrons between
elements or ions `id1` and `id2` with charges `charge1` and `charge2`
respectively according to the expression
Expand Down Expand Up @@ -136,4 +138,4 @@ def deltaN(id1, id2, charge1=0, charge2=0, missingIsZero=True):
2.0 * (e1.hardness(charge=charge1) + e2.hardness(charge=charge2))
)
else:
return None
return None
43 changes: 24 additions & 19 deletions minato_namikaze/bot_files/lib/mendeleev/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
# Its taken from https://github.com/lmmentel/mendeleev

# -*- coding: utf-8 -*-

"""module specifying the database models"""

import math
Expand Down Expand Up @@ -39,7 +38,6 @@
"ScreeningConstant",
]


Base = declarative_base()


Expand Down Expand Up @@ -301,9 +299,8 @@ def mass_str(self) -> str:
else:
return "{aw:.3f}".format(aw=self.atomic_weight)
else:
dec = int(abs(
math.floor(math.log10(abs(self.atomic_weight_uncertainty)))
))
dec = int(
abs(math.floor(math.log10(abs(self.atomic_weight_uncertainty)))))
dec = min(dec, 5)
if self.is_radioactive:
return "[{aw:.{dec}f}]".format(aw=self.atomic_weight, dec=dec)
Expand All @@ -320,7 +317,7 @@ def covalent_radius(self) -> float:

@hybrid_method
def hardness(self, charge: int = 0) -> float:
"""
r"""
Return the absolute hardness, calculated as
Args:
charge: Charge of the cation for which the hardness will be calculated
Expand Down Expand Up @@ -349,12 +346,13 @@ def hardness(self, charge: int = 0) -> float:
return None
elif charge < 0:
raise ValueError(
"Charge has to be a non-negative integer, got: {}".format(charge)
"Charge has to be a non-negative integer, got: {}".format(
charge)
)

@hybrid_method
def softness(self, charge: int = 0) -> float:
"""
r"""
Return the absolute softness, calculated as
Args:
charge: Charge of the cation for which the hardness will be calculated
Expand Down Expand Up @@ -400,13 +398,16 @@ def zeff(
if n is None:
n = self.ec.max_n()
elif not isinstance(n, int):
raise ValueError("<n> should be an integer, got: {}".format(type(n)))
raise ValueError(
"<n> should be an integer, got: {}".format(type(n)))

if o is None:
# take the shell with max `l` for a given `n`
o = ORBITALS[max(get_l(x[1]) for x in self.ec.conf.keys() if x[0] == n)]
o = ORBITALS[max(get_l(x[1])
for x in self.ec.conf.keys() if x[0] == n)]
elif o not in ORBITALS:
raise ValueError("<s> should be one of {}".format(", ".join(ORBITALS)))
raise ValueError(
"<s> should be one of {}".format(", ".join(ORBITALS)))

if method.lower() == "slater":
return self.atomic_number - self.ec.slater_screening(n=n, o=o, alle=alle)
Expand All @@ -417,10 +418,11 @@ def zeff(
else:
return sc
else:
raise ValueError("<method> should be one of {}".format("slater, clementi"))
raise ValueError(
"<method> should be one of {}".format("slater, clementi"))

def electrophilicity(self) -> float:
"""
r"""
Calculate electrophilicity index
.. math::
\\omega = \\frac{\\mu}{2\eta}
Expand Down Expand Up @@ -533,7 +535,7 @@ def electronegativity_li_xue(
}

def electronegativity_martynov_batsanov(self) -> float:
"""
r"""
Calculates the electronegativity value according to Martynov and
Batsanov as the average of the ionization energies of the valence
electrons
Expand All @@ -560,7 +562,7 @@ def electronegativity_mulliken(
missing_is_zero: bool = False,
allow_negative_ea: bool = False,
) -> float:
"""
r"""
Return the absolute electronegativity (Mulliken scale), calculated as
Args:
charge: charge of the ion
Expand All @@ -580,7 +582,8 @@ def electronegativity_mulliken(
ea = self.ionenergies.get(charge, None)
else:
raise ValueError(
"Charge has to be a non-negative integer, got: {}".format(charge)
"Charge has to be a non-negative integer, got: {}".format(
charge)
)
return mulliken(
ip, ea, missing_is_zero=missing_is_zero, allow_negative_ea=allow_negative_ea
Expand Down Expand Up @@ -610,7 +613,8 @@ def oxides(self) -> List[str]:

oxide_coeffs = [coeffs(ox) for ox in self.oxistates if ox > 0]
# convert to strings and replace 1 with empty string
normal_coeffs = [[str(c) if c != 1 else "" for c in t] for t in oxide_coeffs]
normal_coeffs = [[str(c) if c != 1 else "" for c in t]
for t in oxide_coeffs]
return [f"{self.symbol}{cme}O{co}" for cme, co in normal_coeffs]

def __str__(self):
Expand Down Expand Up @@ -646,7 +650,8 @@ def fetch_attrs_for_group(attrs: List[str], group: int = 18) -> Tuple[List[Any]]
.all()
)

results = tuple([getattr(member, attr) for member in members] for attr in attrs)
results = tuple([getattr(member, attr)
for member in members] for attr in attrs)
session.close()
return results

Expand Down Expand Up @@ -879,4 +884,4 @@ def __repr__(self):

return "<ScreeningConstant(Z={0:4d}, n={1:3d}, s={2:s}, screening={3:10.4f})>".format(
self.atomic_number, self.n, self.s, self.screening
)
)