sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _dqdv_split_frames(cell, tidy=False, **kwargs): """Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_...
Returns dqdv data as pandas.DataFrames for all cycles. Args: cell (CellpyData-object). tidy (bool): return in wide format if False (default), long (tidy) format if True. Returns: (charge_ica_frame, discharge_ica_frame) where the frames are ...
entailment
def set_data(self, capacity, voltage=None, capacity_label="q", voltage_label="v" ): """Set the data""" logging.debug("setting data (capacity and voltage)") if isinstance(capacity, pd.DataFrame): logging.debug("recieved a pandas.DataFrame") ...
Set the data
entailment
def inspect_data(self, capacity=None, voltage=None, err_est=False, diff_est=False): """check and inspect the data""" logging.debug("inspecting the data") if capacity is None: capacity = self.capacity if voltage is None: voltage = self.voltag...
check and inspect the data
entailment
def pre_process_data(self): """perform some pre-processing of the data (i.e. interpolation)""" logging.debug("pre-processing the data") capacity = self.capacity voltage = self.voltage # performing an interpolation in v(q) space logging.debug(" - interpolating voltage(c...
perform some pre-processing of the data (i.e. interpolation)
entailment
def increment_data(self): """perform the dq-dv transform""" # NOTE TO ASBJOERN: Probably insert method for "binning" instead of # differentiating here # (use self.increment_method as the variable for selecting method for) logging.debug("incrementing data") # ---- shift...
perform the dq-dv transform
entailment
def post_process_data(self, voltage=None, incremental_capacity=None, voltage_step=None): """perform post-processing (smoothing, normalisation, interpolation) of the data""" logging.debug("post-processing data") if voltage is None: voltage = self.vo...
perform post-processing (smoothing, normalisation, interpolation) of the data
entailment
def easybake(ruleset, in_html, out_html): """This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability. """ html = etree.par...
This adheres to the same interface as ``cnxeasybake.scripts.main.easyback``. ``ruleset`` is a string containing the ruleset CSS while ``in_html`` and ``out_html`` are file-like objects, with respective read and write ability.
entailment
def reconstitute(html): """Given a file-like object as ``html``, reconstruct it into models.""" try: htree = etree.parse(html) except etree.XMLSyntaxError: html.seek(0) htree = etree.HTML(html.read()) xhtml = etree.tostring(htree, encoding='utf-8') return adapt_single_html(x...
Given a file-like object as ``html``, reconstruct it into models.
entailment
def collate(binder, ruleset=None, includes=None): """Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder. """ html_formatter = SingleHTMLFormatter(binder, includes) raw_html = io.BytesIO(bytes(html_formatter)) collated_html = io.BytesI...
Given a ``Binder`` as ``binder``, collate the content into a new set of models. Returns the collated binder.
entailment
def adapt_package(package): """Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``. """ navigati...
Adapts ``.epub.Package`` to a ``BinderItem`` and cascades the adaptation downward to ``DocumentItem`` and ``ResourceItem``. The results of this process provide the same interface as ``.models.Binder``, ``.models.Document`` and ``.models.Resource``.
entailment
def adapt_item(item, package, filename=None): """Adapts ``.epub.Item`` to a ``DocumentItem``. """ if item.media_type == 'application/xhtml+xml': try: html = etree.parse(item.data) except Exception as exc: logger.error("failed parsing {}".format(item.name)) ...
Adapts ``.epub.Item`` to a ``DocumentItem``.
entailment
def make_epub(binders, file): """Creates an EPUB file from a binder(s).""" if not isinstance(binders, (list, set, tuple,)): binders = [binders] epub = EPUB([_make_package(binder) for binder in binders]) epub.to_file(epub, file)
Creates an EPUB file from a binder(s).
entailment
def make_publication_epub(binders, publisher, publication_message, file): """Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request. """ if not isinstance(binders, (list, set, tuple,)): binders = [binders] packages = [...
Creates an epub file from a binder(s). Also requires publication information, meant to be used in a EPUB publication request.
entailment
def _make_package(binder): """Makes an ``.epub.Package`` from a Binder'ish instance.""" package_id = binder.id if package_id is None: package_id = hash(binder) package_name = "{}.opf".format(package_id) extensions = get_model_extensions(binder) template_env = jinja2.Environment(trim_...
Makes an ``.epub.Package`` from a Binder'ish instance.
entailment
def _make_resource_from_inline(reference): """Makes an ``models.Resource`` from a ``models.Reference`` of type INLINE. That is, a data: uri""" uri = DataURI(reference.uri) data = io.BytesIO(uri.data) mimetype = uri.mimetype res = Resource('dummy', data, mimetype) res.id = res.filename ...
Makes an ``models.Resource`` from a ``models.Reference`` of type INLINE. That is, a data: uri
entailment
def _make_item(model): """Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource`` """ item = Item(model.id, model.content, model.media_type) return item
Makes an ``.epub.Item`` from a ``.models.Document`` or ``.models.Resource``
entailment
def _node_to_model(tree_or_item, package, parent=None, lucent_id=TRANSLUCENT_BINDER_ID): """Given a tree, parse to a set of models""" if 'contents' in tree_or_item: # It is a binder. tree = tree_or_item # Grab the package metadata, so we have required license info ...
Given a tree, parse to a set of models
entailment
def adapt_single_html(html): """Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder`` """ html_root = etree.fromstring(html) metadata = parse_metadata(html_root.xpath('//*[@data-type="metadata"]')[0]) id_ = metadata['cnx-archive-uri'] or 'book' ...
Adapts a single html document generated by ``.formatters.SingleHTMLFormatter`` to a ``models.Binder``
entailment
def select_ocv_points(cellpydata, cycles=None, selection_method="martin", number_of_points=5, interval=10, relative_voltage=False, report_times=False, direction=None): """Select points from the ocvrlx step...
Select points from the ocvrlx steps. Args: cellpydata: CellpyData-object cycles: list of cycle numbers to process (optional) selection_method: criteria for selecting points martin: select first and last, and then last/2, last/2/2 etc. unti...
entailment
def get_best_fit_parameters_grouped(self): """Returns a dictionary of the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters] for i in range(self.circuits): result_dict['t' + str(...
Returns a dictionary of the best fit.
entailment
def get_best_fit_parameters_translated_grouped(self): """Returns the parameters as a dictionary of the 'real units' for the best fit.""" result_dict = dict() result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters_translated] resul...
Returns the parameters as a dictionary of the 'real units' for the best fit.
entailment
def plot_summary(self, cycles=None): """Convenience function for plotting the summary of the fit""" if cycles is None: cycles = [0] fig1 = plt.figure() ax1 = fig1.add_subplot(221) ax1.set_title('Fit') ax2 = fig1.add_subplot(222) ax2.set_title('OCV') ...
Convenience function for plotting the summary of the fit
entailment
def plot_summary_translated(self): """Convenience function for plotting the summary of the fit (translated)""" fig2 = plt.figure() ax1 = fig2.add_subplot(221) ax1.set_title('OCV (V)') ax2 = fig2.add_subplot(222) ax2.set_title('IR (Ohm)') ax3 = fig2.add_su...
Convenience function for plotting the summary of the fit (translated)
entailment
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) ...
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...
entailment
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: ...
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...
entailment
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. """ def xpath(x): return html.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) try: value = xpath('//*[@data-type=...
Parse the given ``html`` (an etree object) to a tree. The ``id`` is required in order to assign the top-level tree id value.
entailment
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>, ...]} """ def expath(e, x): return e.xpath(x, namespaces=HTML_DOCUMENT_NAMESPACES) for li in e...
Given an etree containing a navigation document structure rooted from the 'nav' element, parse to a tree: {'id': <id>|'subcol', 'title': <title>, 'contents': [<tree>, ...]}
entailment
def parse_resources(html): """Return a list of resource names found in the html metadata section.""" xpath = '//*[@data-type="resources"]//xhtml:li/xhtml:a' for resource in html.xpath(xpath, namespaces=HTML_DOCUMENT_NAMESPACES): yield { 'id': resource.get('href'), 'filename':...
Return a list of resource names found in the html metadata section.
entailment
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 ...
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` ...
entailment
def on_message(self, client, userdata, msg): ''' 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 matc...
Callback for when a ``PUBLISH`` message is received from the broker.
entailment
def _publish_status(self, port): ''' 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 ...
Publish status for specified port. Parameters ---------- port : str Device name/port.
entailment
def _serial_close(self, port): ''' 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: ...
Handle close request. Parameters ---------- port : str Device name/port.
entailment
def _serial_connect(self, port, request): ''' Handle connection request. Parameters ---------- port : str Device name/port. request : dict ''' # baudrate : int # Baud rate such as 9600 or 115200 etc. # bytesize ...
Handle connection request. Parameters ---------- port : str Device name/port. request : dict
entailment
def _serial_send(self, port, payload): ''' 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 connect...
Send data to connected device. Parameters ---------- port : str Device name/port. payload : bytes Payload to send to device.
entailment
def print_datetime_object(dt): """prints a date-object""" 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)
prints a date-object
entailment
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-...
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...
entailment
def check64bit(current_system="python"): """checks if you are on a 64 bit platform""" 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...
checks if you are on a 64 bit platform
entailment
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) '...
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,...
entailment
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"),...
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...
entailment
def populate(self, filename): """Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file. """ if os.path.isfile(filename): fid_st = os.stat(filename) self.name = os.path.abspath(filename) self...
Finds the file-stats and populates the class with stat values. Args: filename (str): name of the file.
entailment
def get_raw(self): """Get a list with information about the file. The returned list contains name, size, last_modified and location. """ return [self.name, self.size, self.last_modified, self.location]
Get a list with information about the file. The returned list contains name, size, last_modified and location.
entailment
def dfsummary_made(self): """check if the summary table exists""" try: empty = self.dfsummary.empty except AttributeError: empty = True return not empty
check if the summary table exists
entailment
def step_table_made(self): """check if the step table exists""" try: empty = self.step_table.empty except AttributeError: empty = True return not empty
check if the step table exists
entailment
def _open_sheet(self, dtypes_dict=None): """Opens sheets and returns it""" 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...
Opens sheets and returns it
entailment
def _validate(self): """Checks that the db-file is ok Returns: True if OK, False if not. """ 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] ...
Checks that the db-file is ok Returns: True if OK, False if not.
entailment
def select_serial_number_row(self, serial_number): """Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame """ sheet = self.table col = self.db_sheet_cols.id rows = sheet.loc[:, c...
Select row for identification number serial_number Args: serial_number: serial number Returns: pandas.DataFrame
entailment
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 """ sheet = self.table col = self.db_sheet_cols.id ro...
Select rows for identification for a list of serial_number. Args: serial_numbers: list (or ndarray) of serial numbers Returns: pandas.DataFrame
entailment
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_s...
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.
entailment
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 tha...
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 ...
entailment
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 ...
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
entailment
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. ...
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...
entailment
def select_batch(self, batch, batch_col_name=None): """selects the rows in column batch_col_number (default: DbSheetCols.batch)""" if not batch_col_name: batch_col_name = self.db_sheet_cols.batch logger.debug("selecting batch - %s" % batch) sheet = self.table ...
selects the rows in column batch_col_number (default: DbSheetCols.batch)
entailment
def main(argv=None): """Parse passed in cooked single HTML.""" 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.a...
Parse passed in cooked single HTML.
entailment
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 em...
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
entailment
def add_md(text, s, level=0): """Adds text to the readme at the given level""" if level > 0: if text != "": text += "\n" text += "#" * level text += " " text += s + "\n" if level > 0: text += "\n" return text
Adds text to the readme at the given level
entailment
def add_ul(text, ul): """Adds an unordered list to the readme""" text += "\n" for li in ul: text += "- " + li + "\n" text += "\n" return text
Adds an unordered list to the readme
entailment
def make_editions_dict(editions): """Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter. """ 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...
Take a reporter editions dict and flatten it, returning a dict for use in the DictWriter.
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
def update_keys(self): """Updates the Google API key with the text value""" 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())
Updates the Google API key with the text value
entailment
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...
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
entailment
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 """ # Create...
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
entailment
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_w...
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: ...
entailment
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 """ username = user.nam...
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
entailment
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 """ ...
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
entailment
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_emb...
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
entailment
async def update_server_data(server): """ Updates the server info for the given server Args: server: The Discord server to update info for """ 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 da...
Updates the server info for the given server Args: server: The Discord server to update info for
entailment
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 """ logger.debug("Removing server from serverdata") # Remove the server from data data = datatools.get_data() if server_id in data["disco...
Remove a server from the server data Args: server_id (int): The server to remove from the server data
entailment
def check_all_servers(): """Checks all servers, removing any that Modis isn't part of any more""" 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: i...
Checks all servers, removing any that Modis isn't part of any more
entailment
def clear_modules(self): """Clears all modules from the list""" 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...
Clears all modules from the list
entailment
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 """ m_button = tk.Label(self.module_selection, text=module_name, bg="whit...
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
entailment
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 """ if self.current_button == self.module_buttons[module_name...
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
entailment
def toggle(self, discord_token, discord_client_id): """Toggles Modis on or off""" if self.state == 'off': self.start(discord_token, discord_client_id) elif self.state == 'on': self.stop()
Toggles Modis on or off
entailment
def start(self, discord_token, discord_client_id): """Start Modis and log it into Discord.""" self.button_toggle_text.set("Stop Modis") self.state = "on" self.status_bar.set_status(1) logger.info("----------------STARTING DISCORD MODIS----------------") # Clear the mod...
Start Modis and log it into Discord.
entailment
def stop(self): """Stop Modis and log it out of Discord.""" 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...
Stop Modis and log it out of Discord.
entailment
def key_changed(self): """Checks if the key name and value fields have been set, and updates the add key button""" if self.key_name.get() and self.key_val.get(): self.button_key_add.state(["!disabled"]) else: self.button_key_add.state(["disabled"])
Checks if the key name and value fields have been set, and updates the add key button
entailment
def key_add(self): """Adds the current API key to the bot's data""" 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("")
Adds the current API key to the bot's data
entailment
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 """ text = "" colour = "#FFFFFF" if status == 0: text = "OFFLINE"...
Updates the status text Args: status (int): The offline/starting/online status of Modis 0: offline, 1: starting, 2: online
entailment
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 """ try: with open(filepath, 'r') as file: return _json.load(file, object_pairs_hook=Orde...
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
entailment
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 """ help_cont...
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
entailment
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 """ import tkinter as tk import tkinte...
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
entailment
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 """ # Simplify reaction info server = reaction.message.server emoji = reaction.emoj...
The on_message event handler for this module Args: reaction (discord.Reaction): Input reaction user (discord.User): The user that added the reaction
entailment
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 """ state, response = datatools.get_compare_version() logger.info("Starting Modis in c...
Start Modis in console format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
entailment
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 """ logger.info("Starting Modis in GUI") import tkinter as tk logger.debug("Loading packa...
Start Modis in gui format. Args: discord_token (str): The bot token for your Discord application discord_client_id: The bot's client ID
entailment
def write_data(data): """ Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis """ sorted_dict = sort_recursive(data) with open(_datafile, 'w') as file: _json.dump(sorted_dict, file, indent=2)
Write the data to the data.json file Args: data (dict): The updated data dictionary for Modis
entailment
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 """ newdict = {} for i in data.items(): if type(i[1]) is dict: newdict[i[0]]...
Recursively sorts all elements in a dictionary Args: data (dict): The dictionary to sort Returns: sorted_dict (OrderedDict): The sorted data dict
entailment
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. """ state, latest_version = compare_latest_version() if state < 0: ...
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.
entailment
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 (s...
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 ...
entailment
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 """ gui = ui_embed.UI( channel, "That SteamID doesn't exist.", "Y...
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
entailment
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 """ gui = ui_embed.UI( channel, "Couldn't get stats off RLTracke...
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
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
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: """ # Create datapacks datapacks = [("Game", post[0], True), ("...
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:
entailment
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 """ gui = ui_embed.UI( channel, "No results", ":c", ...
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
entailment
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 """ duration_string = api_...
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
entailment
async def on_message(message): """The on_message event handler for this module Args: message (discord.Message): Input message """ # Simplify message info server = message.server author = message.author channel = message.channel content = message.content data = datatools.ge...
The on_message event handler for this module Args: message (discord.Message): Input message
entailment
def build(self): """Builds Discord embed GUI Returns: discord.Embed: Built GUI """ if self.colour: embed = discord.Embed( title=self.title, type='rich', description=self.description, colour=self.col...
Builds Discord embed GUI Returns: discord.Embed: Built GUI
entailment
async def send(self): """Send new GUI""" await client.send_typing(self.channel) self.sent_embed = await client.send_message(self.channel, embed=self.built_embed)
Send new GUI
entailment
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 """ datapack = self.built_embed.to_dict()["fields"][index] self.built_embed.set_fi...
Updates a particular datapack's data Args: index (int): The index of the datapack data (str): The new value to set for this datapack
entailment
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...
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...
entailment
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 editio...
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.
entailment