code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.data = cellpydata self.step_table = self.data.dataset # hope it works... time_voltage = self.data.get_ocv(direction='up', cycles=cycle) time = time_voltage.Step_Time voltage = time_voltage.Voltage self.time = np.arr...
def set_cellpydata(self, cellpydata, cycle)
Performing fit of the OCV steps in the cycles set by set_cycles() from the data set by set_data() r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start). c is found from using tau / r --> err(c) = err(r) + err(tau) Args: cellpydata (CellpyData): data obje...
6.676257
7.172089
0.930866
# Check if data is set if self.time is []: self.result = [] return try: self.fit_model() except ValueError as e: print(e) except AttributeError as e: print(e)
def run_fit(self)
Performing fit of the OCV steps in the cycles set by set_cycles() from the data set by set_data() r is found by calculating v0 / i_start --> err(r)= err(v0) + err(i_start). c is found from using tau / r --> err(c) = err(r) + err(tau) Returns: None: Resulting best fit param...
5.698886
5.425181
1.050451
def xpath(x): return html.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) try: value = xpath('//*[@data-type="binding"]/@data-value')[0] is_translucent = value == 'translucent' except IndexError: is_translucent = False if is_translucent: id = TRANSLUCENT_BINDER...
def parse_navigation_html_to_tree(html, id)
Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value.
4.280034
4.2307
1.011661
def expath(e, x): return e.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) for li in expath(root, 'xhtml:ol/xhtml:li'): is_subtree = bool([e for e in li.getchildren() if e.tag[e.tag.find('}')+1:] == 'ol']) if is_subtree: # It's a sub-tree and hav...
def _nav_to_tree(root)
Given an etree containing a navigation document structure rooted from the 'nav' element, parse to a tree: {'id': <id>|'subcol', 'title': <title>, 'contents': [<tree>, ...]}
4.600165
4.259615
1.079948
xpath = '//*[@data-type="resources"]//xhtml:li/xhtml:a' for resource in html.xpath(xpath, namespaces=HTML_DOCUMENT_NAMESPACES): yield { 'id': resource.get('href'), 'filename': resource.text.strip(), }
def parse_resources(html)
Return a list of resource names found in the html metadata section.
5.230566
4.714599
1.10944
''' Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho....
def on_connect(self, client, userdata, flags, rc)
Callback for when the client receives a ``CONNACK`` response from the broker. Parameters ---------- client : paho.mqtt.client.Client The client instance for this callback. userdata : object The private user data as set in :class:`paho.mqtt.client.Client` ...
3.693389
1.410488
2.618519
''' Callback for when a ``PUBLISH`` message is received from the broker. ''' if msg.topic == 'serial_device/refresh_comports': self.refresh_comports() return match = CRE_MANAGER.match(msg.topic) if match is None: logger.debug('Topic NO...
def on_message(self, client, userdata, msg)
Callback for when a ``PUBLISH`` message is received from the broker.
4.015534
3.814795
1.052621
''' Publish status for specified port. Parameters ---------- port : str Device name/port. ''' if port not in self.open_devices: status = {} else: device = self.open_devices[port].serial properties = ('port',...
def _publish_status(self, port)
Publish status for specified port. Parameters ---------- port : str Device name/port.
2.957548
2.504608
1.180843
''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: logger.error('Er...
def _serial_close(self, port)
Handle close request. Parameters ---------- port : str Device name/port.
4.171185
3.352468
1.244213
''' Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device. ''' if port not in self.open_devices: # Not connected to device. logger.error(...
def _serial_send(self, port, payload)
Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device.
3.129812
2.493119
1.25538
print(dt) print('ctime :', dt.ctime()) print('tuple :', dt.timetuple()) print('ordinal:', dt.toordinal()) print('Year :', dt.year) print('Mon :', dt.month) print('Day :', dt.day)
def print_datetime_object(dt)
prints a date-object
2.802917
2.783219
1.007078
warnings.warn("raw limits have not been subject for testing yet") raw_limits = dict() raw_limits["current_hard"] = 0.1 # There is a bug in PEC raw_limits["current_soft"] = 1.0 raw_limits["stable_current_hard"] = 2.0 raw_limits["stable_current_soft"] = 4.0 ...
def get_raw_limits(self)
Include the settings for how to decide what kind of step you are examining here. The raw limits are 'epsilons' used to check if the current and/or voltage is stable (for example for galvanostatic steps, one would expect that the current is stable (constant) and non-zero). It is expected that di...
3.287483
3.00039
1.095685
if current_system == "python": return sys.maxsize > 2147483647 elif current_system == "os": import platform pm = platform.machine() if pm != ".." and pm.endswith('64'): # recent Python (not Iron) return True else: if 'PROCESSOR_ARCHITEW6432' ...
def check64bit(current_system="python")
checks if you are on a 64 bit platform
5.153514
5.063335
1.01781
# abbrevs = ( # (1 << 50L, 'PB'), # (1 << 40L, 'TB'), # (1 << 30L, 'GB'), # (1 << 20L, 'MB'), # (1 << 10L, 'kB'), # (1, 'b') # ) abbrevs = ( (1 << 50, 'PB'), (1 << 40, 'TB'), (1 << 30, 'GB'), (1 << 20, 'MB'), (1 << ...
def humanize_bytes(b, precision=1)
Return a humanized string representation of a number of b. Assumes `from __future__ import division`. >>> humanize_bytes(1) '1 byte' >>> humanize_bytes(1024) '1.0 kB' >>> humanize_bytes(1024*123) '123.0 kB' >>> humanize_bytes(1024*12342) '12.1 MB' >>> humanize_bytes(1024*12342,...
1.545673
1.661515
0.930279
# This does not work for numpy-arrays if option == "to_float": d = (xldate - 25589) * 86400.0 else: try: d = datetime.datetime(1899, 12, 30) + \ datetime.timedelta(days=xldate + 1462 * datemode) # date_format = "%Y-%m-%d %H:%M:%S:%f" # with micr...
def xldate_as_datetime(xldate, datemode=0, option="to_datetime")
Converts a xls date stamp to a more sensible format. Args: xldate (str): date stamp in Excel format. datemode (int): 0 for 1900-based, 1 for 1904-based. option (str): option in ("to_datetime", "to_float", "to_string"), return value Returns: datetime (datetime object...
3.727803
3.666554
1.016705
if os.path.isfile(filename): fid_st = os.stat(filename) self.name = os.path.abspath(filename) self.full_name = filename self.size = fid_st.st_size self.last_modified = fid_st.st_mtime self.last_accessed = fid_st.st_atime ...
def populate(self, filename)
Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file.
2.51739
2.406379
1.046132
return [self.name, self.size, self.last_modified, self.location]
def get_raw(self)
Get a list with information about the file. The returned list contains name, size, last_modified and location.
8.980975
3.288914
2.730681
try: empty = self.dfsummary.empty except AttributeError: empty = True return not empty
def dfsummary_made(self)
check if the summary table exists
5.681494
4.421165
1.285067
try: empty = self.step_table.empty except AttributeError: empty = True return not empty
def step_table_made(self)
check if the step table exists
6.465894
5.230394
1.236216
table_name = self.db_sheet_table header_row = self.db_header_row nrows = self.nrows if dtypes_dict is None: dtypes_dict = self.dtypes_dict rows_to_skip = self.skiprows logging.debug(f"Trying to open the file {self.db_file}") logging.debug(f"...
def _open_sheet(self, dtypes_dict=None)
Opens sheets and returns it
2.719804
2.691007
1.010701
probably_good_to_go = True sheet = self.table identity = self.db_sheet_cols.id # check if you have unique srnos id_col = sheet.loc[:, identity] if any(id_col.duplicated()): warnings.warn( "your database is corrupt: duplicates" ...
def _validate(self)
Checks that the db-file is ok Returns: True if OK, False if not.
8.06035
7.763752
1.038203
sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col] == serial_number return sheet.loc[rows, :]
def select_serial_number_row(self, serial_number)
Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame
9.596291
9.896134
0.969701
sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, col].isin(serial_numbers) return sheet.loc[rows, :]
def select_all(self, serial_numbers)
Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame
8.483437
8.86384
0.957084
r = self.select_serial_number_row(serial_number) if r.empty: warnings.warn("missing serial number") return txt1 = 80 * "=" txt1 += "\n" txt1 += f" serial number {serial_number}\n" txt1 = 80 * "-" txt1 += "\n" txt2 = "" ...
def print_serial_number_info(self, serial_number, print_to_screen=True)
Print information about the run. Args: serial_number: serial number. print_to_screen: runs the print statement if True, returns txt if not. Returns: txt if print_to_screen is False, else None.
3.093735
2.934284
1.054341
sheet = self.table identity = self.db_sheet_cols.id exists = self.db_sheet_cols.exists cellname = self.db_sheet_cols.cell_name search_string = "" if not isinstance(slurry, (list, tuple)): slurry = [slurry, ] first = True for slur in...
def filter_by_slurry(self, slurry, appender="_")
Filters sheet/table by slurry name. Input is slurry name or list of slurry names, for example 'es030' or ["es012","es033","es031"]. Args: slurry (str or list of strings): slurry names. appender (chr): char that surrounds slurry names. Returns: List ...
3.927335
3.745008
1.048685
if not isinstance(column_names, (list, tuple)): column_names = [column_names, ] sheet = self.table identity = self.db_sheet_cols.id exists = self.db_sheet_cols.exists criterion = True for column_name in column_names: _criterion = sheet....
def filter_by_col(self, column_names)
filters sheet/table by columns (input is column header) The routine returns the serial numbers with values>1 in the selected columns. Args: column_names (list): the column headers. Returns: pandas.DataFrame
4.384507
4.537438
0.966296
sheet = self.table identity = self.db_sheet_cols.id exists_col_number = self.db_sheet_cols.exists exists = sheet.loc[:, exists_col_number] > 0 if min_val is not None and max_val is not None: criterion1 = sheet.loc[:, column_name] >= min_val cri...
def filter_by_col_value(self, column_name, min_val=None, max_val=None)
filters sheet/table by column. The routine returns the serial-numbers with min_val <= values >= max_val in the selected column. Args: column_name (str): column name. min_val (int): minimum value of serial number. max_val (int): maximum value of serial number...
2.52861
2.695098
0.938226
if not batch_col_name: batch_col_name = self.db_sheet_cols.batch logger.debug("selecting batch - %s" % batch) sheet = self.table identity = self.db_sheet_cols.id exists_col_number = self.db_sheet_cols.exists criterion = sheet.loc[:, batch_col_name] ...
def select_batch(self, batch, batch_col_name=None)
selects the rows in column batch_col_number (default: DbSheetCols.batch)
5.120159
4.326698
1.183387
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('collated_html', type=argparse.FileType('r'), help='Path to the collated html' ' file (use - for stdin)') parser.add_argument('-d', '--dump-tree', action='store_true', ...
def main(argv=None)
Parse passed in cooked single HTML.
4.217336
4.088513
1.031508
hex_number = int(hex_str, 16) # Create embed UI object gui = ui_embed.UI( channel, "", "#{}".format(hex_str), modulename=modulename, colour=hex_number, thumbnail=image, ) return gui
def success(channel, image, hex_str)
Creates an embed UI containing a hex color message Args: channel (discord.Channel): The Discord channel to bind the embed to image (str): The url of the image to add hex_str (str): The hex value Returns: ui (ui_embed.UI): The embed UI object that was created
9.129038
5.754333
1.586463
if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
def add_md(text, s, level=0)
Adds text to the readme at the given level
3.02318
2.813849
1.074393
text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
def add_ul(text, ul)
Adds an unordered list to the readme
2.959753
2.910642
1.016873
d = {} nums = ['1', '2', '3', '4', '5', '6'] num_counter = 0 for k, date_dict in editions.items(): d['edition%s' % nums[num_counter]] = k if date_dict['start'] is not None: d['start_e%s' % nums[num_counter]] = date_dict['start'].isoformat() if date_dict['end'] is...
def make_editions_dict(editions)
Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter.
2.304765
2.245586
1.026354
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.761753
3.748638
1.003499
from ...main import add_api_key add_api_key("google_api_key", self.google_api_key.get()) add_api_key("soundcloud_client_id", self.soundcloud_client_id.get())
def update_keys(self)
Updates the Google API key with the text value
4.257895
3.486625
1.221208
# Create embed UI object gui = ui_embed.UI( channel, "{} updated".format(module_name), "{} is now {}".format(module_name, "activated" if module_state else "deactivated"), modulename=modulename ) return gui
def modify_module(channel, module_name, module_state)
Creates an embed UI containing the module modified message Args: channel (discord.Channel): The Discord channel to bind the embed to module_name (str): The name of the module that was updated module_state (bool): The current state of the module Returns: embed: The created embed
6.691116
5.38261
1.243099
# Create embed UI object gui = ui_embed.UI( channel, "Prefix updated", "Modis prefix is now `{}`".format(new_prefix), modulename=modulename ) return gui
def modify_prefix(channel, new_prefix)
Creates an embed UI containing the prefix modified message Args: channel (discord.Channel): The Discord channel to bind the embed to new_prefix (str): The value of the new prefix Returns: embed: The created embed
12.592265
10.677318
1.179347
username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick warning_count_text = "warnings" if warnings != 1 else "warning" warning_text = "{} {}".format(warnings, warning_count_text) result_text = "at {} you will be banned".for...
def user_warning(channel, user, warnings, max_warnings)
Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to warn warnings (str): The warnings for the user max_warnings (str): The maximum warnings for the user Returns: ...
4.754348
4.001694
1.188084
username = user.name if isinstance(user, discord.Member): if user.nick is not None: username = user.nick # Create embed UI object gui = ui_embed.UI( channel, "Banned {}".format(username), "{} has been banned from this server".format(username), m...
def user_ban(channel, user)
Creates an embed UI containing an user warning message Args: channel (discord.Channel): The Discord channel to bind the embed to user (discord.User): The user to ban Returns: ui (ui_embed.UI): The embed UI object
5.515864
3.925706
1.405063
# Create embed UI object gui = ui_embed.UI( channel, "Maximum Warnings Changed", "Users must now have {} warnings to be banned " "(this won't ban existing users with warnings)".format(max_warnings), modulename=modulename ) return gui
def warning_max_changed(channel, max_warnings)
Creates an embed UI containing an error message Args: channel (discord.Channel): The Discord channel to bind the embed to max_warnings (int): The new maximum warnings Returns: ui (ui_embed.UI): The embed UI object
14.639746
9.026434
1.621875
# Create embed UI object gui = ui_embed.UI( channel, title, description, modulename=modulename ) return gui
def error(channel, title, description)
Creates an embed UI containing an error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed description (str): The description for the error Returns: ui (ui_embed.UI): The embed UI object
13.479514
7.509982
1.79488
data = datatools.get_data() # Add the server to server data if it doesn't yet exist send_welcome_message = False if server.id not in data["discord"]["servers"]: logger.debug("Adding new server to serverdata") data["discord"]["servers"][server.id] = {"prefix": "!"} if "mute_...
async def update_server_data(server)
Updates the server info for the given server Args: server: The Discord server to update info for
2.954366
2.967388
0.995611
logger.debug("Removing server from serverdata") # Remove the server from data data = datatools.get_data() if server_id in data["discord"]["servers"]: data["discord"]["servers"].pop(server_id) datatools.write_data(data)
def remove_server_data(server_id)
Remove a server from the server data Args: server_id (int): The server to remove from the server data
4.058723
3.891347
1.043012
data = datatools.get_data() for server_id in data["discord"]["servers"]: is_in_client = False for client_server in client.servers: if server_id == client_server.id: is_in_client = True break if not is_in_client: remove_server_...
def check_all_servers()
Checks all servers, removing any that Modis isn't part of any more
3.517548
3.227755
1.089782
for child in self.module_selection.winfo_children(): child.destroy() self.clear_ui() tk.Label(self.module_ui, text="Start Modis and select a module").grid( column=0, row=0, padx=0, pady=0, sticky="W E N S") if self.current_button is not None: ...
def clear_modules(self)
Clears all modules from the list
4.736226
4.670494
1.014074
m_button = tk.Label(self.module_selection, text=module_name, bg="white", anchor="w") m_button.grid(column=0, row=len(self.module_selection.winfo_children()), padx=0, pady=0, sticky="W E N S") self.module_buttons[module_name] = m_button m_button.bind("<Button-1>", lambda e: self...
def add_module(self, module_name, module_ui)
Adds a module to the list Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
2.661449
2.891927
0.920303
if self.current_button == self.module_buttons[module_name]: return self.module_buttons[module_name].config(bg="#cacaca") if self.current_button is not None: self.current_button.config(bg="white") self.current_button = self.module_buttons[module_name] ...
def module_selected(self, module_name, module_ui)
Called when a module is selected Args: module_name (str): The name of the module module_ui: The function to call to create the module's UI
2.57184
2.632182
0.977075
if self.state == 'off': self.start(discord_token, discord_client_id) elif self.state == 'on': self.stop()
def toggle(self, discord_token, discord_client_id)
Toggles Modis on or off
2.492804
2.351469
1.060105
self.button_toggle_text.set("Stop Modis") self.state = "on" self.status_bar.set_status(1) logger.info("----------------STARTING DISCORD MODIS----------------") # Clear the module list self.module_frame.clear_modules() # Start Modis from modis....
def start(self, discord_token, discord_client_id)
Start Modis and log it into Discord.
3.559962
3.352429
1.061905
self.button_toggle_text.set("Start Modis") self.state = "off" logger.info("Stopping Discord Modis") from ._client import client asyncio.run_coroutine_threadsafe(client.logout(), client.loop) self.status_bar.set_status(0)
def stop(self)
Stop Modis and log it out of Discord.
9.631688
6.270966
1.535918
if self.key_name.get() and self.key_val.get(): self.button_key_add.state(["!disabled"]) else: self.button_key_add.state(["disabled"])
def key_changed(self)
Checks if the key name and value fields have been set, and updates the add key button
3.209743
2.25257
1.424925
from .main import add_api_key add_api_key(self.key_name.get(), self.key_val.get()) # Clear the text fields self.key_name.set("") self.key_val.set("")
def key_add(self)
Adds the current API key to the bot's data
4.021824
3.809076
1.055853
text = "" colour = "#FFFFFF" if status == 0: text = "OFFLINE" colour = "#EF9A9A" elif status == 1: text = "STARTING" colour = "#FFE082" elif status == 2: text = "ONLINE" colour = "#A5D6A7" ...
def set_status(self, status)
Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online
2.946585
2.622724
1.123483
try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=OrderedDict) except Exception as e: logger.error("Could not load file {}".format(filepath)) logger.exception(e) return {}
def get_help_data(filepath)
Get the json data from a help file Args: filepath (str): The file path for the help file Returns: data: The json data from a help file
2.656391
2.858773
0.929207
help_contents = get_help_data(filepath) datapacks = [] # Add the content for d in help_contents: heading = d content = "" if "commands" in d.lower(): for c in help_contents[d]: if "name" not in c: continue ...
def get_help_datapacks(filepath, prefix="!")
Load help text from a file and give it as datapacks Args: filepath (str): The file to load help text from prefix (str): The prefix to use for commands Returns: datapacks (list): The datapacks from the file
2.975983
3.113802
0.955739
import tkinter as tk import tkinter.ttk as ttk help_contents = get_help_data(filepath) text = tk.Text(parent, wrap='word', font=("Helvetica", 10)) text.grid(row=0, column=0, sticky="W E N S") text.tag_config("heading", font=("Helvetica", 14)) text.tag_config("command", font=("Courier...
def add_help_text(parent, filepath, prefix="!")
Load help text from a file and adds it to the parent Args: parent: A tk or ttk object filepath (str): The file to load help text from prefix (str): The prefix to use for commands
2.112089
2.082919
1.014004
# Simplify reaction info server = reaction.message.server emoji = reaction.emoji data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Commands section if user != reaction.message.channel.server.me: if serve...
async def on_reaction_add(reaction, user)
The on_message event handler for this module Args: reaction (discord.Reaction): Input reaction user (discord.User): The user that added the reaction
2.951065
2.965164
0.995245
state, response = datatools.get_compare_version() logger.info("Starting Modis in console") logger.info(response) import threading import asyncio logger.debug("Loading packages") from modis.discord_modis import main as discord_modis_console from modis.reddit_modis import main as ...
def console(discord_token, discord_client_id)
Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
2.95826
2.70462
1.09378
logger.info("Starting Modis in GUI") import tkinter as tk logger.debug("Loading packages") from modis.discord_modis import gui as discord_modis_gui from modis.reddit_modis import gui as reddit_modis_gui from modis.facebook_modis import gui as facebook_modis_gui logger.debug("Initial...
def gui(discord_token, discord_client_id)
Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
3.125327
2.900995
1.077329
sorted_dict = sort_recursive(data) with open(_datafile, 'w') as file: _json.dump(sorted_dict, file, indent=2)
def write_data(data)
Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis
6.259609
5.985445
1.045805
newdict = {} for i in data.items(): if type(i[1]) is dict: newdict[i[0]] = sort_recursive(i[1]) else: newdict[i[0]] = i[1] return OrderedDict(sorted(newdict.items(), key=lambda item: (compare_type(type(item[1])), item[0])))
def sort_recursive(data)
Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict
2.470296
2.526881
0.977607
state, latest_version = compare_latest_version() if state < 0: return -1, "A new version of Modis is available (v{})".format(latest_version) elif state == 0: return 0, "You are running the latest version of Modis (v{})".format(version) else: return 1, "You are running a pre...
def get_compare_version()
Get the version comparison info. Returns: (tuple) state (int): -1 for lower version, 0 for same version, 1 for higher version than latest. response (str): The response string.
3.523472
3.207631
1.098466
# Create datapacks datapacks = [("Platform", platform, False)] for stat in stats: # Add stats if stat[0] in ("Duel 1v1", "Doubles 2v2", "Solo Standard 3v3", "Standard 3v3"): stat_name = "__" + stat[0] + "__" stat_value = "**" + stat[1] + "**" else: ...
def success(channel, stats, name, platform, dp)
Creates an embed UI containing the Rocket League stats Args: channel (discord.Channel): The Discord channel to bind the embed to stats (tuple): Tuples of (field, value, percentile) name (str): The name of the player platform (str): The playfor to search on, can be 'steam', 'ps', or ...
4.953006
4.310205
1.149135
gui = ui_embed.UI( channel, "That SteamID doesn't exist.", "You can get your SteamID by going to your profile page and looking at the url, " "or you can set a custom ID by going to edit profile on your profile page.", modulename=modulename, colour=0x0088FF )...
def fail_steamid(channel)
Creates an embed UI for invalid SteamIDs Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
10.1432
8.153712
1.243998
gui = ui_embed.UI( channel, "Couldn't get stats off RLTrackerNetwork.", "Maybe the API changed, please tell Infraxion.", modulename=modulename, colour=0x0088FF ) return gui
def fail_api(channel)
Creates an embed UI for when the API call didn't work Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
33.339447
22.722794
1.467225
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.23225
3.211288
1.006528
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
5.184668
5.143788
1.007947
# Create datapacks datapacks = [("Game", post[0], True), ("Upvotes", post[2], True)] # Create embed UI object gui = ui_embed.UI( channel, "Link", post[1], modulename=modulename, colour=0xFF8800, thumbnail=post[1], datapacks=datapacks ) ...
def success(channel, post)
Creates an embed UI containing the Reddit posts Args: channel (discord.Channel): The Discord channel to bind the embed to post (tuple): Tuples of (field, value, percentile) Returns:
8.968092
7.626122
1.17597
gui = ui_embed.UI( channel, "No results", ":c", modulename=modulename, colour=0xFF8800 ) return gui
def no_results(channel)
Creates an embed UI for when there were no results Args: channel (discord.Channel): The Discord channel to bind the embed to Returns: ui (ui_embed.UI): The embed UI object
17.130762
11.555493
1.482478
duration_string = api_music.duration_to_string(duration) if duration <= 0: return "---" time_counts = int(round((progress / duration) * TIMEBAR_LENGTH)) if time_counts > TIMEBAR_LENGTH: time_counts = TIMEBAR_LENGTH if duration > 0: bar = "│" + (TIMEBAR_PCHAR * time_co...
def make_timebar(progress=0, duration=0)
Makes a new time bar string Args: progress: How far through the current song we are (in seconds) duration: The duration of the current song (in seconds) Returns: timebar (str): The time bar string
3.276514
3.542698
0.924864
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.468103
3.440303
1.008081
if self.colour: embed = discord.Embed( title=self.title, type='rich', description=self.description, colour=self.colour) else: embed = discord.Embed( title=self.title, type='r...
def build(self)
Builds Discord embed GUI Returns: discord.Embed: Built GUI
2.828333
2.67601
1.056922
await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
async def send(self)
Send new GUI
5.883445
5.287488
1.112711
datapack = self.built_embed.to_dict()["fields"][index] self.built_embed.set_field_at(index, name=datapack["name"], value=data, inline=datapack["inline"])
def update_data(self, index, data)
Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack
5.322135
5.177539
1.027928
variations_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for variation_key, variation_value in data["variations"].items(): try: variations...
def suck_out_variations_only(reporters)
Builds a dictionary of variations to canonical reporters. The dictionary takes the form of: { "A. 2d": ["A.2d"], ... "P.R.": ["Pen. & W.", "P.R.R.", "P."], } In other words, it's a dictionary that maps each variation to a list of reporters that it could be possib...
3.02415
3.175874
0.952226
editions_out = {} for reporter_key, data_list in reporters.items(): # For each reporter key... for data in data_list: # For each book it maps to... for edition_key, edition_value in data["editions"].items(): try: editions_out[editi...
def suck_out_editions(reporters)
Builds a dictionary mapping edition keys to their root name. The dictionary takes the form of: { "A.": "A.", "A.2d": "A.", "A.3d": "A.", "A.D.": "A.D.", ... } In other words, this lets you go from an edition match to its parent key.
3.582977
3.423826
1.046483
names = {} for reporter_key, data_list in reporters.items(): for data in data_list: abbrevs = data['editions'].keys() # Sort abbreviations by start date of the edition sort_func = lambda x: str(data['editions'][x]['start']) + x abbrevs = sorted(abbrev...
def names_to_abbreviations(reporters)
Build a dict mapping names to their variations Something like: { "Atlantic Reporter": ['A.', 'A.2d'], } Note that the abbreviations are sorted by start date.
3.393392
3.288722
1.031827
# Get player ID and name Rocket League Tracker Network webpage = requests.get( "https://rocketleague.tracker.network/profile/{}/{}".format(platform, player) ).text try: # Get player ID playerid_index = webpage.index("/live?ids=") + len("/live?ids=") playerid_end_in...
def check_rank(player, platform="steam")
Gets the Rocket League stats and name and dp of a UserID Args: player (str): The UserID of the player we want to rank check platform (str): The platform to check for, can be 'steam', 'ps', or 'xbox' Returns: success (bool): Whether the rank check was successful package (tuple):...
3.833692
3.563154
1.075927
channel = client.get_channel(channel_id) if channel is None: logger.info("{} is not a channel".format(channel_id)) return # Check that it's enabled in the server data = datatools.get_data() if not data["discord"]["servers"][channel.server.id][modulename]["activated"]: ...
def send_message(channel_id, message)
Send a message to a channel Args: channel_id (str): The id of the channel to send the message to message (str): The message to send to the channel
4.161166
4.293518
0.969174
future = _asyncio.run_coroutine_threadsafe(async_function, client.loop) result = future.result() return result
def runcoro(async_function)
Runs an asynchronous function without needing to use await - useful for lambda Args: async_function (Coroutine): The asynchronous function to run
4.82528
5.249746
0.919145
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() if not data["discord"]["servers"][server.id][_data.modulename]["activated"]: return # Only reply to server messages and...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
5.813117
5.698864
1.020048
from ...main import add_api_key add_api_key("reddit_api_user_agent", self.reddit_api_user_agent.get()) add_api_key("reddit_api_client_id", self.reddit_api_client_id.get()) add_api_key("reddit_api_client_secret", self.reddit_api_client_secret.get())
def update_keys(self)
Updates the Google API key with the text value
2.716383
2.493923
1.089201
data = datatools.get_data() server_id = channel.server.id _dir = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) _dir_modules = "{}/../".format(_dir) if not os.path.isfile("{}/{}/_data.py".format(_dir_modules, module_name)): await client.send_typing(channel) ...
async def activate_module(channel, module_name, activate)
Changes a modules activated/deactivated state for a server Args: channel: The channel to send the message to module_name: The name of the module to change state for activate: The activated/deactivated state of the module
2.686509
2.632733
1.020426
data = datatools.get_data() server_id = channel.server.id if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3 if "warnings" not in data["discord"]["servers"][server_id][_data.modulena...
async def warn_user(channel, user)
Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to
2.016828
1.962819
1.027516
data = datatools.get_data() server_id = channel.server.id try: await client.ban(user) except discord.errors.Forbidden: await client.send_typing(channel) embed = ui_embed.error(channel, "Ban Error", "I do not have the permissions to ban that person.") await embed.se...
async def ban_user(channel, user)
Bans a user from a server Args: channel: The channel to send the warning message in user: The user to give the warning to
3.105301
3.071017
1.011164
_dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) module_dir = "{}/../{}".format(_dir, module_name, "_help.json") if os.path.isdir(module_dir): module_help_path = "{}/{}".format(module_dir, "_help.json") if os.path.isfile(module_help_path): ...
def get_help_datapacks(module_name, server_prefix)
Get the help datapacks for a module Args: module_name (str): The module to get help data for server_prefix (str): The command prefix for this server Returns: datapacks (list): The help datapacks for the module
2.84214
2.831522
1.00375
datapacks = [] _dir = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) for module_name in os.listdir("{}/../".format(_dir)): if not module_name.startswith("_") and not module_name.startswith("!"): help_command = "`{}help {}`".format(server_prefix, mo...
def get_help_commands(server_prefix)
Get the help commands for all modules Args: server_prefix: The server command prefix Returns: datapacks (list): A list of datapacks for the help commands for all the modules
3.467795
3.090765
1.121986
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: # Comma...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
3.011278
3.019016
0.997437
# Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.get_data() # Only reply to server messages and don't reply to myself if server is not None and author != channel.server.me: prefix ...
async def on_message(message)
The on_message event handler for this module Args: message (discord.Message): Input message
2.641267
2.631391
1.003753
if topic_channel is not None: try: channel_message = "Topic channel is now `{}`.".format(topic_channel.name) except Exception as e: logger.exception(e) channel_message = "Topic channel has been updated." else: channel_message = "Topic channel has...
def topic_update(channel, topic_channel)
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to topic_channel: The new topic channel Returns: embed: The created embed
5.420123
5.108436
1.061014
# Create embed UI object gui = ui_embed.UI( channel, err_title, err_message, modulename=modulename, colour=modulecolor_error ) return gui
def error_message(channel, err_title, err_message)
Creates an embed UI for the topic update Args: channel (discord.Channel): The Discord channel to bind the embed to err_title: The title for the error err_message: The message for the error Returns: embed: The created embed
12.621381
11.911576
1.059589
logger.debug("Clearing root cache") if os.path.isdir(_root_songcache_dir): for filename in os.listdir(_root_songcache_dir): file_path = os.path.join(_root_songcache_dir, filename) try: if os.path.isfile(file_path): os.unlink(file_path) ...
def clear_cache_root()
Clears everything in the song cache
2.004451
1.920916
1.043487
if self.state == 'off': self.state = 'starting' self.prev_queue = [] await self.set_topic("") # Init the music player await self.msetup(text_channel) # Queue the song await self.enqueue(query, index, stop_current, shuf...
async def play(self, author, text_channel, query, index=None, stop_current=False, shuffle=False)
The play command Args: author (discord.Member): The member that called the command text_channel (discord.Channel): The channel where the command was called query (str): The argument that was passed with the command index (str): Whether to play next or at the end ...
4.422714
4.552378
0.971517
self.logger.debug("destroy command") self.state = 'destroyed' await self.set_topic("") self.nowplayinglog.debug("---") self.nowplayingauthorlog.debug("---") self.nowplayingsourcelog.debug("---") self.timelog.debug(_timebar.make_timebar()) self.p...
async def destroy(self)
Destroy the whole gui and music player
4.66751
4.398261
1.061217
self.logger.debug("toggle command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): await self.pause() else: await self.resume() ...
async def toggle(self)
Toggles between pause and resume command
4.346364
3.498307
1.242419
self.logger.debug("pause command") if not self.state == 'ready': return if self.streamer is None: return try: if self.streamer.is_playing(): self.streamer.pause() self.pause_time = self.vclient.loop.time() ...
async def pause(self)
Pauses playback if playing
5.464334
4.838497
1.129345
self.logger.debug("resume command") if not self.state == 'ready': return if self.streamer is None: return try: if not self.streamer.is_playing(): play_state = "Streaming" if self.is_live else "Playing" self....
async def resume(self)
Resumes playback if paused
5.098827
4.764505
1.070169
if not self.state == 'ready': logger.debug("Trying to skip from wrong state '{}'".format(self.state)) return if query == "": query = "1" elif query == "all": query = str(len(self.queue) + 1) try: num = int(query) ...
async def skip(self, query="1")
The skip command Args: query (str): The number of items to skip
3.190114
3.210371
0.99369
if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.state)) return if index == "": self.statuslog.error("Must provide index to remove") return elif index == "all": self.queue = [] ...
async def remove(self, index="")
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
2.220737
2.17077
1.023018
if not self.state == 'ready': logger.debug("Trying to rewind from wrong state '{}'".format(self.state)) return if query == "": query = "1" try: num = int(query) except TypeError: self.statuslog.error("Rewind argument...
async def rewind(self, query="1")
The rewind command Args: query (str): The number of items to skip
2.711597
2.734034
0.991793