_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q30400
SubsCenterProvider._search_url_titles
train
def _search_url_titles(self, title): """Search the URL titles by kind for the given `title`. :param str title: title to search for. :return: the URL titles by kind. :rtype: collections.defaultdict """ # make the search logger.info('Searching title name for %r', ...
python
{ "resource": "" }
q30401
Video.age
train
def age(self): """Age of the video""" if self.exists:
python
{ "resource": "" }
q30402
RegistrableExtensionManager.register
train
def register(self, entry_point): """Register an extension :param str entry_point: extension to register (entry point syntax). :raise: ValueError if already registered. """ if entry_point in self.registered_extensions: raise ValueError('Extension already registered')...
python
{ "resource": "" }
q30403
RegistrableExtensionManager.unregister
train
def unregister(self, entry_point): """Unregister a provider :param str entry_point: provider to unregister (entry point syntax). """ if entry_point not in self.registered_extensions: raise ValueError('Extension not registered') ep = EntryPoint.parse(entry_point) ...
python
{ "resource": "" }
q30404
hash_opensubtitles
train
def hash_opensubtitles(video_path): """Compute a hash using OpenSubtitles' algorithm. :param str video_path: path of the video. :return: the hash. :rtype: str """ bytesize = struct.calcsize(b'<q') with open(video_path, 'rb') as f: filesize = os.path.getsize(video_path) file...
python
{ "resource": "" }
q30405
hash_thesubdb
train
def hash_thesubdb(video_path): """Compute a hash using TheSubDB's algorithm. :param str video_path: path of the video. :return: the hash. :rtype: str """ readsize = 64 * 1024 if os.path.getsize(video_path) < readsize: return with open(video_path, 'rb') as f:
python
{ "resource": "" }
q30406
hash_napiprojekt
train
def hash_napiprojekt(video_path): """Compute a hash using NapiProjekt's algorithm. :param str video_path: path of the video.
python
{ "resource": "" }
q30407
hash_shooter
train
def hash_shooter(video_path): """Compute a hash using Shooter's algorithm :param string video_path: path of the video :return: the hash :rtype: string """ filesize = os.path.getsize(video_path) readsize = 4096 if os.path.getsize(video_path) < readsize * 2: return None offse...
python
{ "resource": "" }
q30408
sanitize
train
def sanitize(string, ignore_characters=None): """Sanitize a string to strip special characters. :param str string: the string to sanitize. :param set ignore_characters: characters to ignore. :return: the sanitized string. :rtype: str """ # only deal with strings if string is None: ...
python
{ "resource": "" }
q30409
sanitize_release_group
train
def sanitize_release_group(string): """Sanitize a `release_group` string to remove content in square brackets. :param str string: the release group to sanitize. :return: the sanitized release group. :rtype: str """ # only deal with strings if string is None:
python
{ "resource": "" }
q30410
subliminal
train
def subliminal(ctx, addic7ed, legendastv, opensubtitles, subscenter, cache_dir, debug): """Subtitles, faster than your thoughts.""" # create cache directory try: os.makedirs(cache_dir) except OSError: if not os.path.isdir(cache_dir): raise # configure cache region.co...
python
{ "resource": "" }
q30411
cache
train
def cache(ctx, clear_subliminal): """Cache management.""" if clear_subliminal: for file in glob.glob(os.path.join(ctx.parent.params['cache_dir'], cache_file) + '*'): os.remove(file)
python
{ "resource": "" }
q30412
LegendasTVProvider.search_titles
train
def search_titles(self, title): """Search for titles matching the `title`. :param str title: the title to search for. :return: found titles. :rtype: dict """ # make the query logger.info('Searching title %r', title) r = self.session.get(self.server_url +...
python
{ "resource": "" }
q30413
LegendasTVProvider.get_archives
train
def get_archives(self, title_id, language_code): """Get the archive list from a given `title_id` and `language_code`. :param int title_id: title id. :param int language_code: language code. :return: the archives. :rtype: list of :class:`LegendasTVArchive` """ lo...
python
{ "resource": "" }
q30414
check_video
train
def check_video(video, languages=None, age=None, undefined=False): """Perform some checks on the `video`. All the checks are optional. Return `False` if any of this check fails: * `languages` already exist in `video`'s :attr:`~subliminal.video.Video.subtitle_languages`. * `video` is older than...
python
{ "resource": "" }
q30415
search_external_subtitles
train
def search_external_subtitles(path, directory=None): """Search for external subtitles from a video `path` and their associated language. Unless `directory` is provided, search will be made in the same directory as the video file. :param str path: path to the video. :param str directory: directory to s...
python
{ "resource": "" }
q30416
scan_video
train
def scan_video(path): """Scan a video from a `path`. :param str path: existing path to the video. :return: the scanned video. :rtype: :class:`~subliminal.video.Video` """ # check for non-existing path if not os.path.exists(path): raise ValueError('Path does not exist') # check...
python
{ "resource": "" }
q30417
scan_archive
train
def scan_archive(path): """Scan an archive from a `path`. :param str path: existing path to the archive. :return: the scanned video. :rtype: :class:`~subliminal.video.Video` """ # check for non-existing path if not os.path.exists(path): raise ValueError('Path does not exist') ...
python
{ "resource": "" }
q30418
scan_videos
train
def scan_videos(path, age=None, archives=True): """Scan `path` for videos and their subtitles. See :func:`refine` to find additional information for the video. :param str path: existing directory path to scan. :param datetime.timedelta age: maximum age of the video or archive. :param bool archives...
python
{ "resource": "" }
q30419
download_best_subtitles
train
def download_best_subtitles(videos, languages, min_score=0, hearing_impaired=False, only_one=False, compute_score=None, pool_class=ProviderPool, **kwargs): """List and download the best matching subtitles. The `videos` must pass the `languages` and `undefined` (`only_one`) checks of...
python
{ "resource": "" }
q30420
save_subtitles
train
def save_subtitles(video, subtitles, single=False, directory=None, encoding=None): """Save subtitles on filesystem. Subtitles are saved in the order of the list. If a subtitle with a language has already been saved, other subtitles with the same language are silently ignored. The extension used is `.l...
python
{ "resource": "" }
q30421
ProviderPool.list_subtitles_provider
train
def list_subtitles_provider(self, provider, video, languages): """List subtitles with a single provider. The video and languages are checked against the provider. :param str provider: name of the provider. :param video: video to list subtitles for. :type video: :class:`~sublimi...
python
{ "resource": "" }
q30422
ProviderPool.download_best_subtitles
train
def download_best_subtitles(self, subtitles, video, languages, min_score=0, hearing_impaired=False, only_one=False, compute_score=None): """Download the best matching subtitles. :param subtitles: the subtitles to use. :type subtitles: list of :class:`~subliminal....
python
{ "resource": "" }
q30423
get_scores
train
def get_scores(video): """Get the scores dict for the given `video`. This will return either :data:`episode_scores` or :data:`movie_scores` based on the type of the `video`. :param video: the video to compute the score against. :type video: :class:`~subliminal.video.Video` :return: the scores dict...
python
{ "resource": "" }
q30424
compute_score
train
def compute_score(subtitle, video, hearing_impaired=None): """Compute the score of the `subtitle` against the `video` with `hearing_impaired` preference. :func:`compute_score` uses the :meth:`Subtitle.get_matches <subliminal.subtitle.Subtitle.get_matches>` method and applies the scores (either from :data:`...
python
{ "resource": "" }
q30425
Provider.check
train
def check(cls, video): """Check if the `video` can be processed. The `video` is considered invalid if not an instance of :attr:`video_types` or if the :attr:`required_hash` is not present in :attr:`~subliminal.video.Video.hashes` attribute of the `video`.
python
{ "resource": "" }
q30426
Addic7edProvider._get_show_ids
train
def _get_show_ids(self): """Get the ``dict`` of show ids per series by querying the `shows.php` page. :return: show id per series, lower case and without quotes. :rtype: dict """ # get the show page logger.info('Getting show ids') r = self.session.get(self.serve...
python
{ "resource": "" }
q30427
Addic7edProvider.get_show_id
train
def get_show_id(self, series, year=None, country_code=None): """Get the best matching show id for `series`, `year` and `country_code`. First search in the result of :meth:`_get_show_ids` and fallback on a search with :meth:`_search_show_id`. :param str series: series of the episode. :p...
python
{ "resource": "" }
q30428
TVsubtitlesProvider.get_episode_ids
train
def get_episode_ids(self, show_id, season): """Get episode ids from the show id and the season. :param int show_id: show id. :param int season: season of the episode. :return: episode ids per episode number. :rtype: dict """ # get the page of the season of the s...
python
{ "resource": "" }
q30429
refine
train
def refine(video, embedded_subtitles=True, **kwargs): """Refine a video by searching its metadata. Several :class:`~subliminal.video.Video` attributes can be found: * :attr:`~subliminal.video.Video.resolution` * :attr:`~subliminal.video.Video.video_codec` * :attr:`~subliminal.video.Video.aud...
python
{ "resource": "" }
q30430
get_series_episode
train
def get_series_episode(series_id, season, episode): """Get an episode of a series. :param int series_id: id of the series. :param int season: season number of the episode. :param int episode:
python
{ "resource": "" }
q30431
TVDBClient.get_series_episodes
train
def get_series_episodes(self, id, page=1): """Get series episodes""" # perform the request params = {'page': page} r = self.session.get(self.base_url + '/series/{}/episodes'.format(id), params=params)
python
{ "resource": "" }
q30432
TVDBClient.query_series_episodes
train
def query_series_episodes(self, id, absolute_number=None, aired_season=None, aired_episode=None, dvd_season=None, dvd_episode=None, imdb_id=None, page=1): """Query series episodes""" # perform the request params = {'absoluteNumber': absolute_number, 'airedSeason': a...
python
{ "resource": "" }
q30433
checked
train
def checked(response): """Check a response status before returning it. :param response: a response from a XMLRPC call to OpenSubtitles. :return: the response. :raise: :class:`OpenSubtitlesError` """ status_code = int(response['status'][:3]) if status_code == 401: raise Unauthorized...
python
{ "resource": "" }
q30434
retry_until_ok
train
def retry_until_ok(func, *args, **kwargs): """Retry code block until it succeeds. If it does not succeed in 120 attempts, the function re-raises any error the function raised on its last attempt. """ max_tries = 120 for i in range(max_tries): try: return func(*args, **kwarg...
python
{ "resource": "" }
q30435
DocManagerBase.apply_update
train
def apply_update(self, doc, update_spec): """Apply an update operation to a document.""" # Helper to cast a key for a list or dict, or raise ValueError def _convert_or_raise(container, key): if isinstance(container, dict): return key elif isinstance(conta...
python
{ "resource": "" }
q30436
DocManagerBase.bulk_upsert
train
def bulk_upsert(self, docs, namespace, timestamp): """Upsert each document in a set of documents. This method may be overridden to upsert many documents at
python
{ "resource": "" }
q30437
log_startup_info
train
def log_startup_info(): """Log info about the current environment.""" LOG.always("Starting mongo-connector version: %s", __version__) if "dev" in __version__: LOG.warning( "This is a development version (%s) of mongo-connector", __version__ ) LOG.always("Python version: %s", ...
python
{ "resource": "" }
q30438
Connector.from_config
train
def from_config(cls, config): """Create a new Connector instance from a Config object.""" auth_key = None password_file = config["authentication.passwordFile"] if password_file is not None: try: auth_key = open(config["authentication.passwordFile"]).read() ...
python
{ "resource": "" }
q30439
Connector.join
train
def join(self): """ Joins thread, stops it from running """
python
{ "resource": "" }
q30440
Connector.write_oplog_progress
train
def write_oplog_progress(self): """ Writes oplog progress to file provided by user """ if self.oplog_checkpoint is None: return None with self.oplog_progress as oplog_prog: oplog_dict = oplog_prog.get_dict() items = [[name, util.bson_ts_to_long(oplog_dic...
python
{ "resource": "" }
q30441
Connector.read_oplog_progress
train
def read_oplog_progress(self): """Reads oplog progress from file provided by user. This method is only called once before any threads are spanwed. """ if self.oplog_checkpoint is None: return None # Check for empty file try: if os.stat(self.oplog...
python
{ "resource": "" }
q30442
Connector.copy_uri_options
train
def copy_uri_options(hosts, mongodb_uri): """Returns a MongoDB URI to hosts with the options from mongodb_uri. """ if "?" in mongodb_uri: options = mongodb_uri.split("?", 1)[1] else:
python
{ "resource": "" }
q30443
Connector.oplog_thread_join
train
def oplog_thread_join(self): """Stops all the OplogThreads """ LOG.info("MongoConnector: Stopping all OplogThreads")
python
{ "resource": "" }
q30444
_character_matches
train
def _character_matches(name1, name2): """Yield the number of characters that match the beginning of each string. """ if name1[0] == "*": for i in range(len(name2) + 1): yield 1, i if
python
{ "resource": "" }
q30445
wildcards_overlap
train
def wildcards_overlap(name1, name2): """Return true if two wildcard patterns can match the same string.""" if not name1 and not name2: return True if not name1 or not name2:
python
{ "resource": "" }
q30446
_validate_namespaces
train
def _validate_namespaces(namespaces): """Validate wildcards and renaming in namespaces. Target namespaces should have the same number of wildcards as the source. No target namespaces overlap exactly with each other. Logs a warning when wildcard namespaces have a chance of overlapping. """ for s...
python
{ "resource": "" }
q30447
_merge_namespace_options
train
def _merge_namespace_options( namespace_set=None, ex_namespace_set=None, gridfs_set=None, dest_mapping=None, namespace_options=None, include_fields=None, exclude_fields=None, ): """Merges namespaces options together. The first is the set of excluded namespaces and the second is a ma...
python
{ "resource": "" }
q30448
match_replace_regex
train
def match_replace_regex(regex, src_namespace, dest_namespace): """Return the new mapped namespace if the src_namespace matches the regex.""" match = regex.match(src_namespace)
python
{ "resource": "" }
q30449
namespace_to_regex
train
def namespace_to_regex(namespace): """Create a RegexObject from a wildcard namespace.""" db_name, coll_name = namespace.split(".", 1) # A database name cannot contain a '.' character db_regex = re.escape(db_name).replace(r"\*", "([^.]*)") # But
python
{ "resource": "" }
q30450
NamespaceConfig._register_namespace_and_command
train
def _register_namespace_and_command(self, namespace): """Add a Namespace and the corresponding command namespace.""" self._add_namespace(namespace) # Add the namespace for commands on this database cmd_name = namespace.source_name.split(".", 1)[0]
python
{ "resource": "" }
q30451
NamespaceConfig._add_namespace
train
def _add_namespace(self, namespace): """Add an included and possibly renamed Namespace.""" src_name = namespace.source_name if "*" in src_name:
python
{ "resource": "" }
q30452
NamespaceConfig._add_plain_namespace
train
def _add_plain_namespace(self, namespace): """Add an included and possibly renamed non-wildcard Namespace.""" src_name = namespace.source_name target_name = namespace.dest_name src_names = self._reverse_plain.setdefault(target_name, set()) src_names.add(src_name) if len(s...
python
{ "resource": "" }
q30453
NamespaceConfig.lookup
train
def lookup(self, plain_src_ns): """Given a plain source namespace, return the corresponding Namespace object, or None if it is not included. """ # Ignore the namespace if it is excluded. if plain_src_ns in self._ex_namespace_set: return None # Include all name...
python
{ "resource": "" }
q30454
NamespaceConfig.map_namespace
train
def map_namespace(self, plain_src_ns): """Given a plain source namespace, return the corresponding plain target namespace, or None if it is not included. """
python
{ "resource": "" }
q30455
NamespaceConfig.gridfs_namespace
train
def gridfs_namespace(self, plain_src_ns): """Given a plain source namespace, return the corresponding plain target namespace if this namespace is a gridfs collection. """
python
{ "resource": "" }
q30456
NamespaceConfig.unmap_namespace
train
def unmap_namespace(self, plain_target_ns): """Given a plain target namespace, return the corresponding source namespace. """ # Return the same namespace if there are no included namespaces. if not self._regex_map and not self._plain: return plain_target_ns s...
python
{ "resource": "" }
q30457
NamespaceConfig.map_db
train
def map_db(self, plain_src_db): """Given a plain source database, return the list of target databases. Individual collections in a database can be mapped to different target databases, so map_db can return multiple databases. This function must return all target database names so we mak...
python
{ "resource": "" }
q30458
NamespaceConfig.projection
train
def projection(self, plain_src_name): """Return the projection for the given source namespace.""" mapped = self.lookup(plain_src_name) if not mapped: return None fields = mapped.include_fields or mapped.exclude_fields if
python
{ "resource": "" }
q30459
NamespaceConfig.get_included_databases
train
def get_included_databases(self): """Return the databases we want to include, or empty list for all. """ databases = set() databases.update(self._plain_db.keys())
python
{ "resource": "" }
q30460
DocManager._meta_collections
train
def _meta_collections(self): """Provides the meta collections currently being used """ if self.use_single_meta_collection: yield self.meta_collection_name else: for
python
{ "resource": "" }
q30461
DocManager.upsert
train
def upsert(self, doc, namespace, timestamp): """Update or insert a document into Mongo """ database, coll = self._db_and_collection(namespace) meta_collection_name = self._get_meta_collection(namespace) self.meta_database[meta_collection_name].replace_one( {self.id_...
python
{ "resource": "" }
q30462
DocManager.remove
train
def remove(self, document_id, namespace, timestamp): """Removes document from Mongo The input is a python dictionary that represents a mongo document. The documents has ns and _ts fields. """ database, coll = self._db_and_collection(namespace) meta_collection = self._ge...
python
{ "resource": "" }
q30463
DocManager.search
train
def search(self, start_ts, end_ts): """Called to query Mongo for documents in a time range. """ for meta_collection_name in self._meta_collections(): meta_coll = self.meta_database[meta_collection_name]
python
{ "resource": "" }
q30464
DocManager.get_last_doc
train
def get_last_doc(self): """Returns the last document stored in Mongo. """ def docs_by_ts(): for meta_collection_name in self._meta_collections(): meta_coll = self.meta_database[meta_collection_name] for
python
{ "resource": "" }
q30465
DocManager.upsert
train
def upsert(self, doc, namespace, timestamp): """Adds a document to the doc dict. """ # Allow exceptions to be triggered (for testing purposes) if doc.get("_upsert_exception"):
python
{ "resource": "" }
q30466
DocManager.insert_file
train
def insert_file(self, f, namespace, timestamp): """Inserts a file to the doc dict. """ doc = f.get_metadata()
python
{ "resource": "" }
q30467
DocManager.remove
train
def remove(self, document_id, namespace, timestamp): """Removes the document from the doc dict. """ try: entry = self.doc_dict[document_id] entry.doc = None
python
{ "resource": "" }
q30468
DocManager.search
train
def search(self, start_ts, end_ts): """Searches through all documents and finds all documents that were modified or deleted within the range. Since we have very few documents in the doc dict when this is called, linear search is fine. This method is only used by rollbacks to query ...
python
{ "resource": "" }
q30469
DocManager.get_last_doc
train
def get_last_doc(self): """Searches through the doc dict to find the document that was modified or deleted most recently."""
python
{ "resource": "" }
q30470
DocManager._search
train
def _search(self): """Returns all documents in the doc dict. This function is not a part of the DocManager API, and is only used to simulate searching all documents from a backend. """ results = [] for _id in
python
{ "resource": "" }
q30471
OplogThread._should_skip_entry
train
def _should_skip_entry(self, entry): """Determine if this oplog entry should be skipped. This has the possible side effect of modifying the entry's namespace and filtering fields from updates and inserts. """ # Don't replicate entries resulting from chunk moves if entry....
python
{ "resource": "" }
q30472
OplogThread.join
train
def join(self): """Stop this thread from managing the oplog. """
python
{ "resource": "" }
q30473
OplogThread._find_field
train
def _find_field(cls, field, doc): """Find the field in the document which matches the given field. The field may be in dot notation, eg "a.b.c". Returns a list with a single tuple (path, field_value) or the empty list if the field is not present. """
python
{ "resource": "" }
q30474
OplogThread._find_update_fields
train
def _find_update_fields(cls, field, doc): """Find the fields in the update document which match the given field. Both the field and the top level keys in the doc may be in dot notation, eg "a.b.c". Returns a list of tuples (path, field_value) or the empty list if the field is not presen...
python
{ "resource": "" }
q30475
OplogThread.filter_oplog_entry
train
def filter_oplog_entry(self, entry, include_fields=None, exclude_fields=None): """Remove fields from an oplog entry that should not be replicated. NOTE: this does not support array indexing, for example 'a.b.2'""" if not include_fields and not exclude_fields: return entry el...
python
{ "resource": "" }
q30476
OplogThread.get_oplog_cursor
train
def get_oplog_cursor(self, timestamp=None): """Get a cursor to the oplog after the given timestamp, excluding no-op entries. If no timestamp is specified, returns a cursor to the entire oplog. """ query = {"op": {"$ne": "n"}} if timestamp is None: cursor = se...
python
{ "resource": "" }
q30477
OplogThread.get_collection
train
def get_collection(self, namespace): """Get a pymongo collection from a namespace."""
python
{ "resource": "" }
q30478
OplogThread._get_oplog_timestamp
train
def _get_oplog_timestamp(self, newest_entry): """Return the timestamp of the latest or earliest entry in the oplog. """ sort_order = pymongo.DESCENDING if newest_entry else pymongo.ASCENDING curr = ( self.oplog.find({"op": {"$ne": "n"}}).sort("$natural", sort_order).limit(-1)...
python
{ "resource": "" }
q30479
OplogThread.init_cursor
train
def init_cursor(self): """Position the cursor appropriately. The cursor is set to either the beginning of the oplog, or wherever it was last left off. Returns the cursor and True if the cursor is empty. """ timestamp = self.read_last_checkpoint() if timestamp i...
python
{ "resource": "" }
q30480
OplogThread.update_checkpoint
train
def update_checkpoint(self, checkpoint): """Store the current checkpoint in the oplog progress dictionary. """ if checkpoint is not None and checkpoint != self.checkpoint: self.checkpoint = checkpoint with self.oplog_progress as oplog_prog: oplog_dict = op...
python
{ "resource": "" }
q30481
OplogThread.read_last_checkpoint
train
def read_last_checkpoint(self): """Read the last checkpoint from the oplog progress dictionary. """ # In versions of mongo-connector 2.3 and before, # we used the repr of the # oplog collection as keys in the oplog_progress dictionary. # In versions thereafter, we use the...
python
{ "resource": "" }
q30482
ClusteredWeningerFeatures.fit
train
def fit(self, blocks, y=None): """ Fit a k-means clustering model using an ordered sequence of blocks. """ self.kmeans.fit(make_weninger_features(blocks)) # set the cluster center closest to the origin to
python
{ "resource": "" }
q30483
evaluate_model_predictions
train
def evaluate_model_predictions(y_true, y_pred, weights=None): """ Evaluate the performance of an extractor model's binary classification predictions, typically at the block level, of whether a block is content or not. Args: y_true (``np.ndarray``) y_pred (``np.ndarray``) wei...
python
{ "resource": "" }
q30484
evaluate_extracted_tokens
train
def evaluate_extracted_tokens(gold_content, extr_content): """ Evaluate the similarity between gold-standard and extracted content, typically for a single HTML document, as another way of evaluating the performance of an extractor model. Args: gold_content (str or Sequence[str]): Gold-stand...
python
{ "resource": "" }
q30485
extract_gold_standard_blocks
train
def extract_gold_standard_blocks(data_dir, fileroot, encoding=None, tokenizer=simple_tokenizer, cetr=False): """ Extract the gold standard block-level content and comments for a single observation identified by ``fileroot``, and write the results to file. Args: ...
python
{ "resource": "" }
q30486
get_filenames
train
def get_filenames(dirname, full_path=False, match_regex=None, extension=None): """ Get all filenames under ``dirname`` that match ``match_regex`` or have file extension equal to ``extension``, optionally prepending the full path. Args: dirname (str): /path/to/dir on disk where files to read are...
python
{ "resource": "" }
q30487
read_html_file
train
def read_html_file(data_dir, fileroot, encoding=None): """ Read the HTML file corresponding to identifier ``fileroot`` in the raw HTML directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) Returns: str """ fname = os.path....
python
{ "resource": "" }
q30488
read_gold_standard_file
train
def read_gold_standard_file(data_dir, fileroot, encoding=None, cetr=False): """ Read the gold standard content file corresponding to identifier ``fileroot`` in the gold standard directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) encoding (str) cet...
python
{ "resource": "" }
q30489
read_gold_standard_blocks_file
train
def read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True): """ Read the gold standard blocks file corresponding to identifier ``fileroot`` in the gold standard blocks directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) split_blocks (bool): ...
python
{ "resource": "" }
q30490
prepare_data
train
def prepare_data(data_dir, fileroot, block_pct_tokens_thresh=0.1): """ Prepare data for a single HTML + gold standard blocks example, uniquely identified by ``fileroot``. Args: data_dir (str) fileroot (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: ...
python
{ "resource": "" }
q30491
prepare_all_data
train
def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1): """ Prepare data for all HTML + gold standard blocks examples in ``data_dir``. Args: data_dir (str) block_pct_tokens_thresh (float): must be in [0.0, 1.0] Returns: List[Tuple[str, List[float, int, List[str]], List[flo...
python
{ "resource": "" }
q30492
str_cast
train
def str_cast(maybe_bytes, encoding='utf-8'): """ Converts any bytes-like input to a string-like output, with respect to python version Parameters ---------- maybe_bytes : if this is a bytes-like object, it will be converted to a string encoding : str, default='utf-8' encoding to be...
python
{ "resource": "" }
q30493
bytes_cast
train
def bytes_cast(maybe_str, encoding='utf-8'): """ Converts any string-like input to a bytes-like output, with respect to python version Parameters ---------- maybe_str : if
python
{ "resource": "" }
q30494
str_dict_cast
train
def str_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs): """ Converts any bytes-like items in input dict to string-like values, with respect to python version Parameters ---------- dict_ : dict any bytes-like objects contained in the dict will be converted to a ...
python
{ "resource": "" }
q30495
bytes_dict_cast
train
def bytes_dict_cast(dict_, include_keys=True, include_vals=True, **kwargs): """ Converts any string-like items in input dict to bytes-like values, with respect to python version Parameters ---------- dict_ : dict any string-like objects contained in the dict will be converted to bytes ...
python
{ "resource": "" }
q30496
str_block_cast
train
def str_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs): """ Converts any bytes-like items in input Block object to string-like values, with respec...
python
{ "resource": "" }
q30497
bytes_block_cast
train
def bytes_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs): """ Converts any string-like items in input Block object to bytes-like values, ...
python
{ "resource": "" }
q30498
dameraulevenshtein
train
def dameraulevenshtein(seq1, seq2): """Calculate the Damerau-Levenshtein distance between sequences. This distance is the number of additions, deletions, substitutions, and transpositions needed to transform the first sequence into the second. Although generally used with strings, any sequences of ...
python
{ "resource": "" }
q30499
load_pickled_model
train
def load_pickled_model(filename, dirname=None): """ Load a pickled ``Extractor`` model from disk. Args: filename (str): Name of pickled model file under ``dirname``. dirname (str): Name of directory on disk containing the pickled model. If None, dragnet's default pickled model d...
python
{ "resource": "" }