INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Parse the texts with spaCy. Make one-hot vectors for the labels.
def preprocess(ops, nlp, rows, get_ids): """Parse the texts with spaCy. Make one-hot vectors for the labels.""" Xs = [] ys = [] for (text1, text2), label in rows: Xs.append((get_ids([nlp(text1)])[0], get_ids([nlp(text2)])[0])) ys.append(label) return Xs, ops.asarray(ys, dtype="float3...
Check whether an array is a cupy array
def is_cupy_array(arr): """Check whether an array is a cupy array""" if cupy is None: return False elif isinstance(arr, cupy.ndarray): return True else: return False
Use GPU if it's available. Returns True if so, False otherwise.
def prefer_gpu(): """Use GPU if it's available. Returns True if so, False otherwise.""" from ._classes.model import Model from .ops import CupyOps if CupyOps.xp is not None: Model.Ops = CupyOps Model.ops = CupyOps() return True else: return False
Pad sentence sequences with EOL markers.
def mark_sentence_boundaries(sequences, drop=0.0): # pragma: no cover """Pad sentence sequences with EOL markers.""" for sequence in sequences: sequence.insert(0, "-EOL-") sequence.insert(0, "-EOL-") sequence.append("-EOL-") sequence.append("-EOL-") return sequences, None
Important: Fragmented(=continuation) messages are not supported since their usage cases are limited - when we don't know the payload length.
def send_text(self, message, opcode=OPCODE_TEXT): """ Important: Fragmented(=continuation) messages are not supported since their usage cases are limited - when we don't know the payload length. """ # Validate message if isinstance(message, bytes): message = ...
Main function.
def main(): """Main function.""" # Get the command line arg args = docopt(__doc__, version="Mackup {}".format(VERSION)) mckp = Mackup() app_db = ApplicationsDatabase() def printAppHeader(app_name): if verbose: print(("\n{0} {1} {0}").format(header("---"), bold(app_name))) ...
Get home and mackup filepaths for given file Args: filename (str) Returns: home_filepath, mackup_filepath (str, str)
def getFilepaths(self, filename): """ Get home and mackup filepaths for given file Args: filename (str) Returns: home_filepath, mackup_filepath (str, str) """ return (os.path.join(os.environ['HOME'], filename), os.path.join(self.m...
Backup the application config files. Algorithm: if exists home/file if home/file is a real file if exists mackup/file are you sure ? if sure rm mackup/file mv home/file mackup/file ...
def backup(self): """ Backup the application config files. Algorithm: if exists home/file if home/file is a real file if exists mackup/file are you sure ? if sure rm mackup/file ...
Restore the application config files. Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else link mackup/file home/file
def restore(self): """ Restore the application config files. Algorithm: if exists mackup/file if exists home/file are you sure ? if sure rm home/file link mackup/file home/file else ...
Uninstall Mackup. Restore any file where it was before the 1st Mackup backup. Algorithm: for each file in config if mackup/file exists if home/file exists delete home/file copy mackup/file home/file ...
def uninstall(self): """ Uninstall Mackup. Restore any file where it was before the 1st Mackup backup. Algorithm: for each file in config if mackup/file exists if home/file exists delete home/file ...
Check if the current env is usable and has everything's required.
def check_for_usable_environment(self): """Check if the current env is usable and has everything's required.""" # Do not let the user run Mackup as root if os.geteuid() == 0: utils.error("Running Mackup as a superuser is useless and" " dangerous. Don't do it!"...
Check if the current env can be used to restore files.
def check_for_usable_restore_env(self): """Check if the current env can be used to restore files.""" self.check_for_usable_environment() if not os.path.isdir(self.mackup_folder): utils.error("Unable to find the Mackup folder: {}\n" "You might want to back up ...
If the Mackup home folder does not exist, create it.
def create_mackup_home(self): """If the Mackup home folder does not exist, create it.""" if not os.path.isdir(self.mackup_folder): if utils.confirm("Mackup needs a directory to store your" " configuration files\n" "Do you want to crea...
Get the list of applications that should be backed up by Mackup. It's the list of allowed apps minus the list of ignored apps. Returns: (set) List of application names to back up
def get_apps_to_backup(self): """ Get the list of applications that should be backed up by Mackup. It's the list of allowed apps minus the list of ignored apps. Returns: (set) List of application names to back up """ # Instantiate the app db app_db =...
Return the application configuration files. Return a list of configuration files describing the apps supported by Mackup. The files return are absolute full path to those files. e.g. /usr/lib/mackup/applications/bash.cfg Only one config file per application should be returned, custom c...
def get_config_files(): """ Return the application configuration files. Return a list of configuration files describing the apps supported by Mackup. The files return are absolute full path to those files. e.g. /usr/lib/mackup/applications/bash.cfg Only one config file ...
Return application names. Return the list of application names that are available in the database. Returns: set of str.
def get_app_names(self): """ Return application names. Return the list of application names that are available in the database. Returns: set of str. """ app_names = set() for name in self.apps: app_names.add(name) return ...
Return the list of pretty app names that are available in the database. Returns: set of str.
def get_pretty_app_names(self): """ Return the list of pretty app names that are available in the database. Returns: set of str. """ pretty_app_names = set() for app_name in self.get_app_names(): pretty_app_names.add(self.get_name(app_name)) ...
Ask the user if he really want something to happen. Args: question(str): What can happen Returns: (boolean): Confirmed or not
def confirm(question): """ Ask the user if he really want something to happen. Args: question(str): What can happen Returns: (boolean): Confirmed or not """ if FORCE_YES: return True while True: answer = input(question + ' <Yes|No>').lower() if ans...
Delete the given file, directory or link. It Should support undelete later on. Args: filepath (str): Absolute full path to a file. e.g. /path/to/file
def delete(filepath): """ Delete the given file, directory or link. It Should support undelete later on. Args: filepath (str): Absolute full path to a file. e.g. /path/to/file """ # Some files have ACLs, let's remove them recursively remove_acl(filepath) # Some files have immu...
Copy a file or a folder (recursively) from src to dst. For simplicity sake, both src and dst must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. copy('/path/to/src_file', '/path/to/dst_file') or copy('/path/to/src_folder', '/path/...
def copy(src, dst): """ Copy a file or a folder (recursively) from src to dst. For simplicity sake, both src and dst must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. copy('/path/to/src_file', '/path/to/dst_file') or cop...
Create a link to a target file or a folder. For simplicity sake, both target and link_to must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: link('/path/to/file', 'path/to/') or...
def link(target, link_to): """ Create a link to a target file or a folder. For simplicity sake, both target and link_to must be absolute path and must include the filename of the file or folder. Also do not include any trailing slash. e.g. link('/path/to/file', '/path/to/link') But not: l...
Recursively set the chmod for files to 0600 and 0700 for folders. It's ok unless we need something more specific. Args: target (str): Root file or folder
def chmod(target): """ Recursively set the chmod for files to 0600 and 0700 for folders. It's ok unless we need something more specific. Args: target (str): Root file or folder """ assert isinstance(target, str) assert os.path.exists(target) file_mode = stat.S_IRUSR | stat.S_I...
Throw an error with the given message and immediately quit. Args: message(str): The message to display.
def error(message): """ Throw an error with the given message and immediately quit. Args: message(str): The message to display. """ fail = '\033[91m' end = '\033[0m' sys.exit(fail + "Error: {}".format(message) + end)
Try to locate the Dropbox folder. Returns: (str) Full path to the current Dropbox folder
def get_dropbox_folder_location(): """ Try to locate the Dropbox folder. Returns: (str) Full path to the current Dropbox folder """ host_db_path = os.path.join(os.environ['HOME'], '.dropbox/host.db') try: with open(host_db_path, 'r') as f_hostdb: data = f_hostdb.read...
Try to locate the Google Drive folder. Returns: (str) Full path to the current Google Drive folder
def get_google_drive_folder_location(): """ Try to locate the Google Drive folder. Returns: (str) Full path to the current Google Drive folder """ gdrive_db_path = 'Library/Application Support/Google/Drive/sync_config.db' yosemite_gdrive_db_path = ('Library/Application Support/Google/Dr...
Try to locate the Box folder. Returns: (str) Full path to the current Box folder
def get_box_folder_location(): """ Try to locate the Box folder. Returns: (str) Full path to the current Box folder """ box_prefs_path = ('Library/Application Support/Box/Box Sync/' 'sync_root_folder.txt') box_home = None box_prefs = os.path.join(os.environ['H...
Try to locate the Copy folder. Returns: (str) Full path to the current Copy folder
def get_copy_folder_location(): """ Try to locate the Copy folder. Returns: (str) Full path to the current Copy folder """ copy_settings_path = 'Library/Application Support/Copy Agent/config.db' copy_home = None copy_settings = os.path.join(os.environ['HOME'], copy_settings_path) ...
Try to locate the iCloud Drive folder. Returns: (str) Full path to the iCloud Drive folder.
def get_icloud_folder_location(): """ Try to locate the iCloud Drive folder. Returns: (str) Full path to the iCloud Drive folder. """ yosemite_icloud_path = '~/Library/Mobile Documents/com~apple~CloudDocs/' icloud_home = os.path.expanduser(yosemite_icloud_path) if not os.path.isdi...
Check if a process with the given name is running. Args: (str): Process name, e.g. "Sublime Text" Returns: (bool): True if the process is running
def is_process_running(process_name): """ Check if a process with the given name is running. Args: (str): Process name, e.g. "Sublime Text" Returns: (bool): True if the process is running """ is_running = False # On systems with pgrep, check if the given process is running...
Remove the ACL of the file or folder located on the given path. Also remove the ACL of any file and folder below the given one, recursively. Args: path (str): Path to the file or folder to remove the ACL for, recursively.
def remove_acl(path): """ Remove the ACL of the file or folder located on the given path. Also remove the ACL of any file and folder below the given one, recursively. Args: path (str): Path to the file or folder to remove the ACL for, recursively. """ # Some fil...
Check if the given path can be synced locally. Check if it makes sense to sync the file at the given path on the current platform. For now we don't sync any file in the ~/Library folder on GNU/Linux. There might be other exceptions in the future. Args: (str): Path to the file or folder to ...
def can_file_be_synced_on_current_platform(path): """ Check if the given path can be synced locally. Check if it makes sense to sync the file at the given path on the current platform. For now we don't sync any file in the ~/Library folder on GNU/Linux. There might be other exceptions in the fu...
Full path to the Mackup configuration files. The full path to the directory when Mackup is storing the configuration files. Returns: str
def fullpath(self): """ Full path to the Mackup configuration files. The full path to the directory when Mackup is storing the configuration files. Returns: str """ return str(os.path.join(self.path, self.directory))
Configure the ConfigParser instance the way we want it. Args: filename (str) or None Returns: SafeConfigParser
def _setup_parser(self, filename=None): """ Configure the ConfigParser instance the way we want it. Args: filename (str) or None Returns: SafeConfigParser """ assert isinstance(filename, str) or filename is None # If we are not overridin...
Warn the user if an old config format is detected.
def _warn_on_old_config(self): """Warn the user if an old config format is detected.""" # Is an old setion is in the config file ? old_sections = ['Allowed Applications', 'Ignored Applications'] for old_section in old_sections: if self._parser.has_section(old_section): ...
Parse the storage engine in the config. Returns: str
def _parse_engine(self): """ Parse the storage engine in the config. Returns: str """ if self._parser.has_option('storage', 'engine'): engine = str(self._parser.get('storage', 'engine')) else: engine = ENGINE_DROPBOX assert is...
Parse the storage path in the config. Returns: str
def _parse_path(self): """ Parse the storage path in the config. Returns: str """ if self.engine == ENGINE_DROPBOX: path = get_dropbox_folder_location() elif self.engine == ENGINE_GDRIVE: path = get_google_drive_folder_location() ...
Parse the storage directory in the config. Returns: str
def _parse_directory(self): """ Parse the storage directory in the config. Returns: str """ if self._parser.has_option('storage', 'directory'): directory = self._parser.get('storage', 'directory') # Don't allow CUSTOM_APPS_DIR as a storage dir...
Parse the applications to ignore in the config. Returns: set
def _parse_apps_to_ignore(self): """ Parse the applications to ignore in the config. Returns: set """ # We ignore nothing by default apps_to_ignore = set() # Is the "[applications_to_ignore]" in the cfg file ? section_title = 'applications_to...
Parse the applications to backup in the config. Returns: set
def _parse_apps_to_sync(self): """ Parse the applications to backup in the config. Returns: set """ # We allow nothing by default apps_to_sync = set() # Is the "[applications_to_sync]" section in the cfg file ? section_title = 'applications_t...
Build tabula-py option from template file Args: file_like_obj: File like object of Tabula app template Returns: `obj`:dict: tabula-py options
def load_template(path_or_buffer): '''Build tabula-py option from template file Args: file_like_obj: File like object of Tabula app template Returns: `obj`:dict: tabula-py options ''' from itertools import groupby from operator import itemgetter path_or_buffer = _stringif...
Convert Tabula app template to tabula-py option Args: template (dict): Tabula app template Returns: `obj`:dict: tabula-py option
def _convert_template_option(template): '''Convert Tabula app template to tabula-py option Args: template (dict): Tabula app template Returns: `obj`:dict: tabula-py option ''' option = {} extraction_method = template.get('extraction_method') if extraction_method == 'guess'...
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.
def deprecated(func): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emmitted when the function is used.""" def newFunc(*args, **kwargs): warnings.warn("Call to deprecated function {}.".format(func.__name__), cate...
Call tabula-java with the given lists of Java options and tabula-py options, as well as an optional path to pass to tabula-java as a regular argument and an optional encoding to use for any required output sent to stderr. tabula-py options are translated into tabula-java options, see :func:`build_o...
def _run(java_options, options, path=None, encoding='utf-8'): """Call tabula-java with the given lists of Java options and tabula-py options, as well as an optional path to pass to tabula-java as a regular argument and an optional encoding to use for any required output sent to stderr. tabula-py op...
Read tables in PDF. Args: input_path (file like obj): File like object of tareget PDF file. output_format (str, optional): Output format of this function (dataframe or json) encoding (str, optional): Encoding type for pandas. Default is 'utf-8' ja...
def read_pdf(input_path, output_format='dataframe', encoding='utf-8', java_options=None, pandas_options=None, multiple_tables=False, **kwargs): '''Read tables in PDF. Args: input_path (file like obj): File like object of tareg...
Read tables in PDF. Args: input_path (file like obj): File like object of tareget PDF file. template_path (file_like_obj): File like object for Tabula app template. pandas_options (dict, optional): Set pandas options like {'header': None}. encodin...
def read_pdf_with_template( input_path, template_path, pandas_options=None, encoding='utf-8', java_options=None, **kwargs): '''Read tables in PDF. Args: input_path (file like obj): File like object of tareget PDF file. template_path (f...
Convert tables from PDF into a file. Args: input_path (file like obj): File like object of tareget PDF file. output_path (str): File path of output file. output_format (str, optional): Output format of this function (csv, json or tsv). Default: csv ...
def convert_into(input_path, output_path, output_format='csv', java_options=None, **kwargs): '''Convert tables from PDF into a file. Args: input_path (file like obj): File like object of tareget PDF file. output_path (str): File path of output file. output_format...
Convert tables from PDFs in a directory. Args: input_dir (str): Directory path. output_format (str, optional): Output format of this function (csv, json or tsv) java_options (list, optional): Set java options like `-Xmx256m`. kwargs (dict): ...
def convert_into_by_batch(input_dir, output_format='csv', java_options=None, **kwargs): '''Convert tables from PDFs in a directory. Args: input_dir (str): Directory path. output_format (str, optional): Output format of this function (csv, json or tsv) java_option...
Extract tables from json. Args: raw_json (list): Decoded list from tabula-java JSON. pandas_options (dict optional): pandas options for `pd.DataFrame()`
def _extract_from(raw_json, pandas_options=None): '''Extract tables from json. Args: raw_json (list): Decoded list from tabula-java JSON. pandas_options (dict optional): pandas options for `pd.DataFrame()` ''' data_frames = [] if pandas_options is None: ...
Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header. Args: pandas_option (dict): pandas options like {'header': None}. columns (list): list of column name.
def _convert_pandas_csv_options(pandas_options, columns): ''' Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header. Args: pandas_option (dict): pandas options like {'header': None}. columns (list): list of column name. ''' _columns = pan...
Build options for tabula-java Args: options (str, optional): Raw option string for tabula-java. pages (str, int, :obj:`list` of :obj:`int`, optional): An optional values specifying pages to extract from. It allows `str`,`int`, :obj:`list` of :obj:`int`. ...
def build_options(kwargs=None): '''Build options for tabula-java Args: options (str, optional): Raw option string for tabula-java. pages (str, int, :obj:`list` of :obj:`int`, optional): An optional values specifying pages to extract from. It allows `str`,`int...
Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage temporary_file_flag (bool): temporary file fl...
def localize_file(path_or_buffer): '''Ensure localize target file. If the target file is remote, this function fetches into local storage. Args: path (str): File path or file like object or URL of target file. Returns: filename (str): file name in local storage tem...
Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer
def _stringify_path(path_or_buffer): '''Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer ''' try: import pathlib _PATHLIB_INSTALLED = True except ImportError: ...
I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast enough for our tastes * TransferError: the sender rejected the transfe...
def receive(args, reactor=reactor, _debug_stash_wormhole=None): """I implement 'wormhole receive'. I return a Deferred that fires with None (for success), or signals one of the following errors: * WrongPasswordError: the two sides didn't use matching passwords * Timeout: something didn't happen fast eno...
the zipfile module does not restore file permissions so we'll do it manually
def _extract_file(self, zf, info, extract_dir): """ the zipfile module does not restore file permissions so we'll do it manually """ out_path = os.path.join(extract_dir, info.filename) out_path = os.path.abspath(out_path) if not out_path.startswith(extract_dir): ...
If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion-service listeners, if necessary). Otherwise if tor_control_port is provided, I will attempt to connect to an existing Tor's control port at the e...
def get_tor(reactor, launch_tor=False, tor_control_port=None, timing=None, stderr=sys.stderr): """ If launch_tor=True, I will try to launch a new Tor process, ask it for its SOCKS and control ports, and use those for outbound connections (and inbound onion...
This looks for an appropriate SSH key to send, possibly querying the user in the meantime. DO NOT CALL after reactor.run as this (possibly) does blocking stuff like asking the user questions (via click.prompt()) Returns a 3-tuple: kind, keyid, pubkey_data
def find_public_key(hint=None): """ This looks for an appropriate SSH key to send, possibly querying the user in the meantime. DO NOT CALL after reactor.run as this (possibly) does blocking stuff like asking the user questions (via click.prompt()) Returns a 3-tuple: kind, keyid, pubkey_data ...
Create a Magic Wormhole and communicate through it. Wormholes are created by speaking the same magic CODE in two different places at the same time. Wormholes are secure against anyone who doesn't use the same code.
def wormhole(context, dump_timing, transit_helper, relay_url, appid): """ Create a Magic Wormhole and communicate through it. Wormholes are created by speaking the same magic CODE in two different places at the same time. Wormholes are secure against anyone who doesn't use the same code. """ ...
Internal helper. This calls the given command (a no-argument callable) with the Config instance in cfg and interprets any errors for the user.
def _dispatch_command(reactor, cfg, command): """ Internal helper. This calls the given command (a no-argument callable) with the Config instance in cfg and interprets any errors for the user. """ cfg.timing.add("command dispatch") cfg.timing.add( "import", when=start, which="top").f...
Send a text message, file, or directory
def send(cfg, **kwargs): """Send a text message, file, or directory""" for name, value in kwargs.items(): setattr(cfg, name, value) with cfg.timing.add("import", which="cmd_send"): from . import cmd_send return go(cmd_send.send, cfg)
Receive a text message, file, or directory (from 'wormhole send')
def receive(cfg, code, **kwargs): """ Receive a text message, file, or directory (from 'wormhole send') """ for name, value in kwargs.items(): setattr(cfg, name, value) with cfg.timing.add("import", which="cmd_receive"): from . import cmd_receive if len(code) == 1: cfg.co...
Add a public-key to a ~/.ssh/authorized_keys file
def ssh_invite(ctx, code_length, user, **kwargs): """ Add a public-key to a ~/.ssh/authorized_keys file """ for name, value in kwargs.items(): setattr(ctx.obj, name, value) from . import cmd_ssh ctx.obj.code_length = code_length ctx.obj.ssh_user = user return go(cmd_ssh.invite, c...
Send your SSH public-key In response to a 'wormhole ssh invite' this will send public-key you specify (if there's only one in ~/.ssh/* that will be sent).
def ssh_accept(cfg, code, key_file, yes, **kwargs): """ Send your SSH public-key In response to a 'wormhole ssh invite' this will send public-key you specify (if there's only one in ~/.ssh/* that will be sent). """ for name, value in kwargs.items(): setattr(cfg, name, value) from ....
Return an (integer) available TCP port on localhost. This briefly listens on the port in question, then closes it right away.
def allocate_tcp_port(): """Return an (integer) available TCP port on localhost. This briefly listens on the port in question, then closes it right away.""" # We want to bind() the socket but not listen(). Twisted (in # tcp.Port.createInternetSocket) would do several other things: # non-blocking, cl...
If the timer fires first, cancel the deferred. If the deferred fires first, cancel the timer.
def _not_forever(self, timeout, d): """If the timer fires first, cancel the deferred. If the deferred fires first, cancel the timer.""" t = self._reactor.callLater(timeout, d.cancel) def _done(res): if t.active(): t.cancel() return res d....
This is a convenience API which returns a Deferred that callbacks with a single chunk of data from another wormhole (and then closes the wormhole). Under the hood, it's just using an instance returned from :func:`wormhole.wormhole`. This is similar to the `wormhole receive` command. :param unicode ...
def receive(reactor, appid, relay_url, code, use_tor=False, launch_tor=False, tor_control_port=None, on_code=None): """ This is a convenience API which returns a Deferred that callbacks with a single chunk of data from anoth...
Get access to a specific table. Creates a new table, if it hasn't been created before, otherwise it returns the cached :class:`~tinydb.Table` object. :param name: The name of the table. :type name: str :param cache_size: How many query results to cache. :param table_cla...
def table(self, name=DEFAULT_TABLE, **options): """ Get access to a specific table. Creates a new table, if it hasn't been created before, otherwise it returns the cached :class:`~tinydb.Table` object. :param name: The name of the table. :type name: str :param c...
Purge a specific table from the database. **CANNOT BE REVERSED!** :param name: The name of the table. :type name: str
def purge_table(self, name): """ Purge a specific table from the database. **CANNOT BE REVERSED!** :param name: The name of the table. :type name: str """ if name in self._table_cache: del self._table_cache[name] proxy = StorageProxy(self._storage, n...
Helper function for processing all documents specified by condition or IDs. A repeating pattern in TinyDB is to run some code on all documents that match a condition or are specified by their ID. This is implemented in this function. The function passed as ``func`` has to be a c...
def process_elements(self, func, cond=None, doc_ids=None, eids=None): """ Helper function for processing all documents specified by condition or IDs. A repeating pattern in TinyDB is to run some code on all documents that match a condition or are specified by their ID. This is ...
Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID
def insert(self, document): """ Insert a new document into the table. :param document: the document to insert :returns: the inserted document's ID """ doc_id = self._get_doc_id(document) data = self._read() data[doc_id] = dict(document) self._wri...
Insert multiple documents into the table. :param documents: a list of documents to insert :returns: a list containing the inserted documents' IDs
def insert_multiple(self, documents): """ Insert multiple documents into the table. :param documents: a list of documents to insert :returns: a list containing the inserted documents' IDs """ doc_ids = [] data = self._read() for doc in documents: ...
Remove all matching documents. :param cond: the condition to check against :type cond: query :param doc_ids: a list of document IDs :type doc_ids: list :returns: a list containing the removed document's ID
def remove(self, cond=None, doc_ids=None, eids=None): """ Remove all matching documents. :param cond: the condition to check against :type cond: query :param doc_ids: a list of document IDs :type doc_ids: list :returns: a list containing the removed document's ID...
Update all matching documents to have a given set of fields. :param fields: the fields that the matching documents will have or a method that will update the documents :type fields: dict | dict -> None :param cond: which documents to update :type cond: query ...
def update(self, fields, cond=None, doc_ids=None, eids=None): """ Update all matching documents to have a given set of fields. :param fields: the fields that the matching documents will have or a method that will update the documents :type fields: dict | dict -> N...
Write back documents by doc_id :param documents: a list of document to write back :param doc_ids: a list of document IDs which need to be written back :returns: a list of document IDs that have been written
def write_back(self, documents, doc_ids=None, eids=None): """ Write back documents by doc_id :param documents: a list of document to write back :param doc_ids: a list of document IDs which need to be written back :returns: a list of document IDs that have been written ""...
Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a list containing the updated document's ID
def upsert(self, document, cond): """ Update a document, if it exist - insert it otherwise. Note: this will update *all* documents matching the query. :param document: the document to insert or the fields to update :param cond: which document to look for :returns: a lis...
Search for all documents matching a 'where' cond. :param cond: the condition to check against :type cond: Query :returns: list of matching documents :rtype: list[Element]
def search(self, cond): """ Search for all documents matching a 'where' cond. :param cond: the condition to check against :type cond: Query :returns: list of matching documents :rtype: list[Element] """ if cond in self._query_cache: return s...
Get exactly one document specified by a query or and ID. Returns ``None`` if the document doesn't exist :param cond: the condition to check against :type cond: Query :param doc_id: the document's ID :returns: the document or None :rtype: Element | None
def get(self, cond=None, doc_id=None, eid=None): """ Get exactly one document specified by a query or and ID. Returns ``None`` if the document doesn't exist :param cond: the condition to check against :type cond: Query :param doc_id: the document's ID :returns...
Check wether the database contains a document matching a condition or an ID. If ``eids`` is set, it checks if the db contains a document with one of the specified. :param cond: the condition use :type cond: Query :param doc_ids: the document IDs to look for
def contains(self, cond=None, doc_ids=None, eids=None): """ Check wether the database contains a document matching a condition or an ID. If ``eids`` is set, it checks if the db contains a document with one of the specified. :param cond: the condition use :type c...
Flush all unwritten data to disk.
def flush(self): """ Flush all unwritten data to disk. """ if self._cache_modified_count > 0: self.storage.write(self.cache) self._cache_modified_count = 0
Run a regex test against a dict value (whole string has to match). >>> Query().f1.matches(r'^\w+$') :param regex: The regular expression to use for matching
def matches(self, regex, flags=0): """ Run a regex test against a dict value (whole string has to match). >>> Query().f1.matches(r'^\w+$') :param regex: The regular expression to use for matching """ return self._generate_test( lambda value: re.match(regex, ...
Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching
def search(self, regex, flags=0): """ Run a regex test against a dict value (only substring string has to match). >>> Query().f1.search(r'^\w+$') :param regex: The regular expression to use for matching """ return self._generate_test( lambda value: r...
Check if a condition is met by any document in a list, where a condition can also be a sequence (e.g. list). >>> Query().f1.any(Query().f2 == 1) Matches:: {'f1': [{'f2': 1}, {'f2': 0}]} >>> Query().f1.any([1, 2, 3]) Matches:: {'f1': [1, 2]} ...
def any(self, cond): """ Check if a condition is met by any document in a list, where a condition can also be a sequence (e.g. list). >>> Query().f1.any(Query().f2 == 1) Matches:: {'f1': [{'f2': 1}, {'f2': 0}]} >>> Query().f1.any([1, 2, 3]) Matche...
Check if the value is contained in a list or generator. >>> Query().f1.one_of(['value 1', 'value 2']) :param items: The list of items to check with
def one_of(self, items): """ Check if the value is contained in a list or generator. >>> Query().f1.one_of(['value 1', 'value 2']) :param items: The list of items to check with """ return self._generate_test( lambda value: value in items, ('one_o...
Sets an object attribute with the correct data type.
def setobjattr(obj, key, value): """Sets an object attribute with the correct data type.""" try: setattr(obj, key, int(value)) except ValueError: try: setattr(obj, key, float(value)) except ValueError: # string if not number try: se...
Return the game file for a certain day matching certain criteria.
def get_scoreboard(year, month, day): """Return the game file for a certain day matching certain criteria.""" try: data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml') except HTTPError: data = os.path.join(PWD, 'default.xml') return data
Return the box score file of a game with matching id.
def get_box_score(game_id): """Return the box score file of a game with matching id.""" year, month, day = get_date_from_game_id(game_id) try: return urlopen(GAME_URL.format(year, month, day, game_id, 'boxscore.xml')) except HTTPError: raise ValueEr...
Return the innings file of a game with matching id.
def get_innings(game_id): """Return the innings file of a game with matching id.""" year, month, day = get_date_from_game_id(game_id) try: return urlopen(INNINGS_URL.format(year, month, day, game_id)) except HTTPError: raise ValueError('Could not find a game with that id.')
Return the standings file for current standings (given current date).
def get_standings(date): """Return the standings file for current standings (given current date).""" try: return urlopen(STANDINGS_URL.format(date.year, date.strftime('%Y/%m/%d'))) except HTTPError: ValueError('Could not find the standings file. ' ...
Return the historical standings file for specified date.
def get_historical_standings(date): """Return the historical standings file for specified date.""" try: url = STANDINGS_HISTORICAL_URL.format(date.year, date.strftime('%Y/%m/%d')) return urlopen(url) except HTTPError: ValueError('Could no...
Return the scoreboard information for games matching the parameters as a dictionary.
def scoreboard(year, month, day, home=None, away=None): """Return the scoreboard information for games matching the parameters as a dictionary. """ # get data data = mlbgame.data.get_scoreboard(year, month, day) # parse data parsed = etree.parse(data) root = parsed.getroot() games = ...
Gets the box score information for the game with matching id.
def box_score(game_id): """Gets the box score information for the game with matching id.""" # get data data = mlbgame.data.get_box_score(game_id) # parse data parsed = etree.parse(data) root = parsed.getroot() linescore = root.find('linescore') result = dict() result['game_id'] = gam...
Massage runs in an inning to 0 if an empty string, or key not found. Otherwise return the value
def value_to_int(attrib, key): """ Massage runs in an inning to 0 if an empty string, or key not found. Otherwise return the value """ val = attrib.get(key, 0) if isinstance(val, str): if val.isspace() or val == '': return 0 return val
Gets the overview information for the game with matching id.
def overview(game_id): """Gets the overview information for the game with matching id.""" output = {} # get data overview = mlbgame.data.get_overview(game_id) # parse data overview_root = etree.parse(overview).getroot() try: output = add_raw_box_score_attributes(output, game_id) ...
Gets player/coach/umpire information for the game with matching id.
def players(game_id): """Gets player/coach/umpire information for the game with matching id.""" # get data data = mlbgame.data.get_players(game_id) # parse data parsed = etree.parse(data) root = parsed.getroot() output = {} output['game_id'] = game_id # get player/coach data fo...
Print object as a scoreboard.
def print_scoreboard(self): """Print object as a scoreboard.""" output = '' # parallel dictionaries with innings and scores innings = [] away = [] home = [] for x in self: innings.append(x['inning']) away.append(x['away']) home....
Return a list of games for a certain day. If the home and away team are the same, it will return the game(s) for that team.
def day(year, month, day, home=None, away=None): """Return a list of games for a certain day. If the home and away team are the same, it will return the game(s) for that team. """ # get the days per month daysinmonth = calendar.monthrange(year, month)[1] # do not even try to get data if day...
Return box score for game matching the game id.
def box_score(game_id): """Return box score for game matching the game id.""" # get box score data data = mlbgame.game.box_score(game_id) # create object with data obj = mlbgame.game.GameBoxScore(data) return obj
Return dictionary of player stats for game matching the game id.
def player_stats(game_id): """Return dictionary of player stats for game matching the game id.""" # get information for that game data = mlbgame.stats.player_stats(game_id) return mlbgame.stats.Stats(data, game_id, True)
Return dictionary of team stats for game matching the game id.
def team_stats(game_id): """Return dictionary of team stats for game matching the game id.""" # get data data = mlbgame.stats.team_stats(game_id) return mlbgame.stats.Stats(data, game_id, False)
Return list of Inning objects for game matching the game id. Using `inning_endpoints=True` will result in objects with additional, undocumented data properties, but also objects that may be missing properties expected by the user. `innings_endpoint`: bool, use more detailed `innings` API endpoint
def game_events(game_id, innings_endpoint=False): """Return list of Inning objects for game matching the game id. Using `inning_endpoints=True` will result in objects with additional, undocumented data properties, but also objects that may be missing properties expected by the user. `innings_endpo...
Return ImportantDates object that contains MLB important dates
def important_dates(year=None): """Return ImportantDates object that contains MLB important dates""" year = datetime.now().year if not year else year data = mlbgame.info.important_dates(year) return mlbgame.info.ImportantDates(data)