_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q33700
ParserUDF._valid_pdf
train
def _valid_pdf(self, path, filename): """Verify that the file exists and has a PDF extension.""" # If path is file, but not PDF. if os.path.isfile(path) and path.lower().endswith(".pdf"): return True else: full_path = os.path.join(path, filename) if os...
python
{ "resource": "" }
q33701
ParserUDF._parse_figure
train
def _parse_figure(self, node, state): """Parse the figure node. :param node: The lxml img node to parse :param state: The global state necessary to place the node in context of the document as a whole. """ if node.tag not in ["img", "figure"]: return stat...
python
{ "resource": "" }
q33702
ParserUDF._parse_paragraph
train
def _parse_paragraph(self, node, state): """Parse a Paragraph of the node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole. """ # Both Paragraphs will share the same parent ...
python
{ "resource": "" }
q33703
ParserUDF._parse_section
train
def _parse_section(self, node, state): """Parse a Section of the node. Note that this implementation currently creates a Section at the beginning of the document and creates Section based on tag of node. :param node: The lxml node to parse :param state: The global state necessa...
python
{ "resource": "" }
q33704
ParserUDF._parse_caption
train
def _parse_caption(self, node, state): """Parse a Caption of the node. :param node: The lxml node to parse :param state: The global state necessary to place the node in context of the document as a whole. """ if node.tag not in ["caption", "figcaption"]: # captions ...
python
{ "resource": "" }
q33705
ParserUDF._parse_node
train
def _parse_node(self, node, state): """Entry point for parsing all node types. :param node: The lxml HTML node to parse :param state: The global state necessary to place the node in context of the document as a whole. :rtype: a *generator* of Sentences """ # ...
python
{ "resource": "" }
q33706
ParserUDF.parse
train
def parse(self, document, text): """Depth-first search over the provided tree. Implemented as an iterative procedure. The structure of the state needed to parse each node is also defined in this function. :param document: the Document context :param text: the structured text of...
python
{ "resource": "" }
q33707
init_logging
train
def init_logging( log_dir=tempfile.gettempdir(), format="[%(asctime)s][%(levelname)s] %(name)s:%(lineno)s - %(message)s", level=logging.INFO, ): """Configures logging to output to the provided log_dir. Will use a nested directory whose name is the current timestamp. :param log_dir: The directo...
python
{ "resource": "" }
q33708
_update_meta
train
def _update_meta(conn_string): """Update Meta class.""" url = urlparse(conn_string) Meta.conn_string = conn_string Meta.DBNAME = url.path[1:] Meta.DBUSER = url.username Meta.DBPWD = url.password Meta.DBHOST = url.hostname Meta.DBPORT = url.port Meta.postgres = url.scheme.startswith("...
python
{ "resource": "" }
q33709
Meta.init
train
def init(cls, conn_string=None): """Return the unique Meta class.""" if conn_string: _update_meta(conn_string) # We initialize the engine within the models module because models' # schema can depend on which data types are supported by the engine Meta.Sess...
python
{ "resource": "" }
q33710
Meta._init_db
train
def _init_db(cls): """ Initialize the storage schema. This call must be performed after all classes that extend Base are declared to ensure the storage schema is initialized. """ # This list of import defines which SQLAlchemy classes will be # initialized when Meta.init(...
python
{ "resource": "" }
q33711
Spacy.model_installed
train
def model_installed(name): """Check if spaCy language model is installed. From https://github.com/explosion/spaCy/blob/master/spacy/util.py :param name: :return: """ data_path = util.get_data_path() if not data_path or not data_path.exists(): raise I...
python
{ "resource": "" }
q33712
Spacy.load_lang_model
train
def load_lang_model(self): """ Load spaCy language model or download if model is available and not installed. Currenty supported spaCy languages en English (50MB) de German (645MB) fr French (1.33GB) es Spanish (377MB) :return: """ ...
python
{ "resource": "" }
q33713
Spacy.enrich_sentences_with_NLP
train
def enrich_sentences_with_NLP(self, all_sentences): """ Enrich a list of fonduer Sentence objects with NLP features. We merge and process the text of all Sentences for higher efficiency. :param all_sentences: List of fonduer Sentence objects for one document :return: """...
python
{ "resource": "" }
q33714
Spacy.split_sentences
train
def split_sentences(self, text): """ Split input text into sentences that match CoreNLP's default format, but are not yet processed. :param text: The text of the parent paragraph of the sentences :return: """ if self.model.has_pipe("sentence_boundary_detector"):...
python
{ "resource": "" }
q33715
Classifier._setup_model_loss
train
def _setup_model_loss(self, lr): """ Setup loss and optimizer for PyTorch model. """ # Setup loss if not hasattr(self, "loss"): self.loss = SoftCrossEntropyLoss() # Setup optimizer if not hasattr(self, "optimizer"): self.optimizer = optim....
python
{ "resource": "" }
q33716
Classifier.save_marginals
train
def save_marginals(self, session, X, training=False): """Save the predicted marginal probabilities for the Candidates X. :param session: The database session to use. :param X: Input data. :param training: If True, these are training marginals / labels; else they are saved as...
python
{ "resource": "" }
q33717
Classifier.predict
train
def predict(self, X, b=0.5, pos_label=1, return_probs=False): """Return numpy array of class predictions for X based on predicted marginal probabilities. :param X: Input data. :param b: Decision boundary *for binary setting only*. :type b: float :param pos_label: Positiv...
python
{ "resource": "" }
q33718
Classifier.save
train
def save(self, model_file, save_dir, verbose=True): """Save current model. :param model_file: Saved model file name. :type model_file: str :param save_dir: Saved model directory. :type save_dir: str :param verbose: Print log or not :type verbose: bool """...
python
{ "resource": "" }
q33719
Classifier.load
train
def load(self, model_file, save_dir, verbose=True): """Load model from file and rebuild the model. :param model_file: Saved model file name. :type model_file: str :param save_dir: Saved model directory. :type save_dir: str :param verbose: Print log or not :type v...
python
{ "resource": "" }
q33720
get_parent_tag
train
def get_parent_tag(mention): """Return the HTML tag of the Mention's parent. These may be tags such as 'p', 'h2', 'table', 'div', etc. If a candidate is passed in, only the tag of its first Mention is returned. :param mention: The Mention to evaluate :rtype: string """ span = _to_span(ment...
python
{ "resource": "" }
q33721
get_prev_sibling_tags
train
def get_prev_sibling_tags(mention): """Return the HTML tag of the Mention's previous siblings. Previous siblings are Mentions which are at the same level in the HTML tree as the given mention, but are declared before the given mention. If a candidate is passed in, only the previous siblings of its firs...
python
{ "resource": "" }
q33722
get_next_sibling_tags
train
def get_next_sibling_tags(mention): """Return the HTML tag of the Mention's next siblings. Next siblings are Mentions which are at the same level in the HTML tree as the given mention, but are declared after the given mention. If a candidate is passed in, only the next siblings of its last Mention ...
python
{ "resource": "" }
q33723
get_ancestor_class_names
train
def get_ancestor_class_names(mention): """Return the HTML classes of the Mention's ancestors. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span(mention) class_names = []...
python
{ "resource": "" }
q33724
get_ancestor_tag_names
train
def get_ancestor_tag_names(mention): """Return the HTML tag of the Mention's ancestors. For example, ['html', 'body', 'p']. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span...
python
{ "resource": "" }
q33725
get_ancestor_id_names
train
def get_ancestor_id_names(mention): """Return the HTML id's of the Mention's ancestors. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span(mention) id_names = [] i = ...
python
{ "resource": "" }
q33726
common_ancestor
train
def common_ancestor(c): """Return the path to the root that is shared between a binary-Mention Candidate. In particular, this is the common path of HTML tags. :param c: The binary-Mention Candidate to evaluate :rtype: list of strings """ span1 = _to_span(c[0]) span2 = _to_span(c[1]) an...
python
{ "resource": "" }
q33727
RNN.init_hidden
train
def init_hidden(self, batch_size): """Initiate the initial state. :param batch_size: batch size. :type batch_size: int :return: Initial state of LSTM :rtype: pair of torch.Tensors of shape (num_layers * num_directions, batch_size, hidden_size) """ b ...
python
{ "resource": "" }
q33728
TensorBoardLogger.add_scalar
train
def add_scalar(self, name, value, step): """Log a scalar variable.""" self.writer.add_scalar(name, value, step)
python
{ "resource": "" }
q33729
mention_to_tokens
train
def mention_to_tokens(mention, token_type="words", lowercase=False): """ Extract tokens from the mention :param mention: mention object. :param token_type: token type that wants to extract. :type token_type: str :param lowercase: use lowercase or not. :type lowercase: bool :return: The ...
python
{ "resource": "" }
q33730
mark_sentence
train
def mark_sentence(s, args): """Insert markers around relation arguments in word sequence :param s: list of tokens in sentence. :type s: list :param args: list of triples (l, h, idx) as per @_mark(...) corresponding to relation arguments :type args: list :return: The marked senten...
python
{ "resource": "" }
q33731
pad_batch
train
def pad_batch(batch, max_len=0, type="int"): """Pad the batch into matrix :param batch: The data for padding. :type batch: list of word index sequences :param max_len: Max length of sequence of padding. :type max_len: int :param type: mask value type. :type type: str :return: The padded...
python
{ "resource": "" }
q33732
DocPreprocessor._generate
train
def _generate(self): """Parses a file or directory of files into a set of ``Document`` objects.""" doc_count = 0 for fp in self.all_files: for doc in self._get_docs_for_path(fp): yield doc doc_count += 1 if doc_count >= self.max_docs: ...
python
{ "resource": "" }
q33733
is_horz_aligned
train
def is_horz_aligned(c): """Return True if all the components of c are horizontally aligned. Horizontal alignment means that the bounding boxes of each Mention of c shares a similar y-axis value in the visual rendering of the document. :param c: The candidate to evaluate :rtype: boolean """ ...
python
{ "resource": "" }
q33734
is_vert_aligned
train
def is_vert_aligned(c): """Return true if all the components of c are vertically aligned. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. :param c: The candidate to evaluate :rtype: boolean """ ret...
python
{ "resource": "" }
q33735
is_vert_aligned_left
train
def is_vert_aligned_left(c): """Return true if all components are vertically aligned on their left border. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. In this function the similarity of the x-axis value is ...
python
{ "resource": "" }
q33736
is_vert_aligned_right
train
def is_vert_aligned_right(c): """Return true if all components vertically aligned on their right border. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. In this function the similarity of the x-axis value is ba...
python
{ "resource": "" }
q33737
is_vert_aligned_center
train
def is_vert_aligned_center(c): """Return true if all the components are vertically aligned on their center. Vertical alignment means that the bounding boxes of each Mention of c shares a similar x-axis value in the visual rendering of the document. In this function the similarity of the x-axis value is...
python
{ "resource": "" }
q33738
same_page
train
def same_page(c): """Return true if all the components of c are on the same page of the document. Page numbers are based on the PDF rendering of the document. If a PDF file is provided, it is used. Otherwise, if only a HTML/XML document is provided, a PDF is created and then used to determine the page ...
python
{ "resource": "" }
q33739
get_horz_ngrams
train
def get_horz_ngrams( mention, attrib="words", n_min=1, n_max=1, lower=True, from_sentence=True ): """Return all ngrams which are visually horizontally aligned with the Mention. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention to evaluate :par...
python
{ "resource": "" }
q33740
get_page_vert_percentile
train
def get_page_vert_percentile( mention, page_width=DEFAULT_WIDTH, page_height=DEFAULT_HEIGHT ): """Return which percentile from the TOP in the page the Mention is located in. Percentile is calculated where the top of the page is 0.0, and the bottom of the page is 1.0. For example, a Mention in at the to...
python
{ "resource": "" }
q33741
get_page_horz_percentile
train
def get_page_horz_percentile( mention, page_width=DEFAULT_WIDTH, page_height=DEFAULT_HEIGHT ): """Return which percentile from the LEFT in the page the Mention is located in. Percentile is calculated where the left of the page is 0.0, and the right of the page is 1.0. Page width and height are bas...
python
{ "resource": "" }
q33742
get_visual_aligned_lemmas
train
def get_visual_aligned_lemmas(mention): """Return a generator of the lemmas aligned visually with the Mention. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention to evaluate. :rtype: a *generator* of lemmas """ spans = _to_spans(mention) ...
python
{ "resource": "" }
q33743
camel_to_under
train
def camel_to_under(name): """ Converts camel-case string to lowercase string separated by underscores. Written by epost (http://stackoverflow.com/questions/1175208). :param name: String to be converted :return: new String with camel-case converted to lowercase, underscored """ s1 = re.sub(...
python
{ "resource": "" }
q33744
get_as_dict
train
def get_as_dict(x): """Return an object as a dictionary of its attributes.""" if isinstance(x, dict): return x else: try: return x._asdict() except AttributeError: return x.__dict__
python
{ "resource": "" }
q33745
UDFRunner._apply_st
train
def _apply_st(self, doc_loader, **kwargs): """Run the UDF single-threaded, optionally with progress bar""" udf = self.udf_class(**self.udf_init_kwargs) # Run single-thread for doc in doc_loader: if self.pb is not None: self.pb.update(1) udf.sessi...
python
{ "resource": "" }
q33746
UDFRunner._apply_mt
train
def _apply_mt(self, doc_loader, parallelism, **kwargs): """Run the UDF multi-threaded using python multiprocessing""" if not Meta.postgres: raise ValueError("Fonduer must use PostgreSQL as a database backend.") def fill_input_queue(in_queue, doc_loader, terminal_signal): ...
python
{ "resource": "" }
q33747
AnnotationMixin.candidate
train
def candidate(cls): """The ``Candidate``.""" return relationship( "Candidate", backref=backref( camel_to_under(cls.__name__) + "s", cascade="all, delete-orphan", cascade_backrefs=False, ), cascade_backrefs=Fa...
python
{ "resource": "" }
q33748
same_document
train
def same_document(c): """Return True if all Mentions in the given candidate are from the same Document. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return all( _to_span(c[i]).sentence.document is not None and _to_span(c[i]).sentence.document == _to_...
python
{ "resource": "" }
q33749
same_table
train
def same_table(c): """Return True if all Mentions in the given candidate are from the same Table. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return all( _to_span(c[i]).sentence.is_tabular() and _to_span(c[i]).sentence.table == _to_span(c[0]).senten...
python
{ "resource": "" }
q33750
same_row
train
def same_row(c): """Return True if all Mentions in the given candidate are from the same Row. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return same_table(c) and all( is_row_aligned(_to_span(c[i]).sentence, _to_span(c[0]).sentence) for i in range(l...
python
{ "resource": "" }
q33751
same_col
train
def same_col(c): """Return True if all Mentions in the given candidate are from the same Col. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return same_table(c) and all( is_col_aligned(_to_span(c[i]).sentence, _to_span(c[0]).sentence) for i in range(l...
python
{ "resource": "" }
q33752
is_tabular_aligned
train
def is_tabular_aligned(c): """Return True if all Mentions in the given candidate are from the same Row or Col. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return same_table(c) and ( is_col_aligned(_to_span(c[i]).sentence, _to_span(c[0]).sentence) or...
python
{ "resource": "" }
q33753
same_cell
train
def same_cell(c): """Return True if all Mentions in the given candidate are from the same Cell. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return all( _to_span(c[i]).sentence.cell is not None and _to_span(c[i]).sentence.cell == _to_span(c[0]).sente...
python
{ "resource": "" }
q33754
same_sentence
train
def same_sentence(c): """Return True if all Mentions in the given candidate are from the same Sentence. :param c: The candidate whose Mentions are being compared :rtype: boolean """ return all( _to_span(c[i]).sentence is not None and _to_span(c[i]).sentence == _to_span(c[0]).sentenc...
python
{ "resource": "" }
q33755
get_max_col_num
train
def get_max_col_num(mention): """Return the largest column number that a Mention occupies. :param mention: The Mention to evaluate. If a candidate is given, default to its last Mention. :rtype: integer or None """ span = _to_span(mention, idx=-1) if span.sentence.is_tabular(): r...
python
{ "resource": "" }
q33756
get_min_col_num
train
def get_min_col_num(mention): """Return the lowest column number that a Mention occupies. :param mention: The Mention to evaluate. If a candidate is given, default to its first Mention. :rtype: integer or None """ span = _to_span(mention) if span.sentence.is_tabular(): return sp...
python
{ "resource": "" }
q33757
get_min_row_num
train
def get_min_row_num(mention): """Return the lowest row number that a Mention occupies. :param mention: The Mention to evaluate. If a candidate is given, default to its first Mention. :rtype: integer or None """ span = _to_span(mention) if span.sentence.is_tabular(): return span....
python
{ "resource": "" }
q33758
get_sentence_ngrams
train
def get_sentence_ngrams(mention, attrib="words", n_min=1, n_max=1, lower=True): """Get the ngrams that are in the Sentence of the given Mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Sentence is being search...
python
{ "resource": "" }
q33759
get_neighbor_sentence_ngrams
train
def get_neighbor_sentence_ngrams( mention, d=1, attrib="words", n_min=1, n_max=1, lower=True ): """Get the ngrams that are in the neighoring Sentences of the given Mention. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose neighbor Sentences...
python
{ "resource": "" }
q33760
get_cell_ngrams
train
def get_cell_ngrams(mention, attrib="words", n_min=1, n_max=1, lower=True): """Get the ngrams that are in the Cell of the given mention, not including itself. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose Cell is being searched :param at...
python
{ "resource": "" }
q33761
get_neighbor_cell_ngrams
train
def get_neighbor_cell_ngrams( mention, dist=1, directions=False, attrib="words", n_min=1, n_max=1, lower=True ): """ Get the ngrams from all Cells that are within a given Cell distance in one direction from the given Mention. Note that if a candidate is passed in, all of its Mentions will be se...
python
{ "resource": "" }
q33762
get_col_ngrams
train
def get_col_ngrams( mention, attrib="words", n_min=1, n_max=1, spread=[0, 0], lower=True ): """Get the ngrams from all Cells that are in the same column as the given Mention. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose column Cells are...
python
{ "resource": "" }
q33763
get_aligned_ngrams
train
def get_aligned_ngrams( mention, attrib="words", n_min=1, n_max=1, spread=[0, 0], lower=True ): """Get the ngrams from all Cells in the same row or column as the given Mention. Note that if a candidate is passed in, all of its Mentions will be searched. :param mention: The Mention whose row and co...
python
{ "resource": "" }
q33764
get_head_ngrams
train
def get_head_ngrams(mention, axis=None, attrib="words", n_min=1, n_max=1, lower=True): """Get the ngrams from the cell in the head of the row or column. More specifically, this returns the ngrams in the leftmost cell in a row and/or the ngrams in the topmost cell in the column, depending on the axis parame...
python
{ "resource": "" }
q33765
_get_table_cells
train
def _get_table_cells(table): """Helper function with caching for table cells and the cells' sentences. This function significantly improves the speed of `get_row_ngrams` primarily by reducing the number of queries that are made (which were previously the bottleneck. Rather than taking a single mention,...
python
{ "resource": "" }
q33766
SoftCrossEntropyLoss.forward
train
def forward(self, input, target): """ Calculate the loss :param input: prediction logits :param target: target probabilities :return: loss """ n, k = input.shape losses = input.new_zeros(n) for i in range(k): cls_idx = input.new_full...
python
{ "resource": "" }
q33767
bbox_horz_aligned
train
def bbox_horz_aligned(box1, box2): """ Returns true if the vertical center point of either span is within the vertical range of the other """ if not (box1 and box2): return False # NEW: any overlap counts # return box1.top <= box2.bottom and box2.top <= box1.bottom box1_top = ...
python
{ "resource": "" }
q33768
bbox_vert_aligned
train
def bbox_vert_aligned(box1, box2): """ Returns true if the horizontal center point of either span is within the horizontal range of the other """ if not (box1 and box2): return False # NEW: any overlap counts # return box1.left <= box2.right and box2.left <= box1.right box1_le...
python
{ "resource": "" }
q33769
bbox_vert_aligned_left
train
def bbox_vert_aligned_left(box1, box2): """ Returns true if the left boundary of both boxes is within 2 pts """ if not (box1 and box2): return False return abs(box1.left - box2.left) <= 2
python
{ "resource": "" }
q33770
bbox_vert_aligned_right
train
def bbox_vert_aligned_right(box1, box2): """ Returns true if the right boundary of both boxes is within 2 pts """ if not (box1 and box2): return False return abs(box1.right - box2.right) <= 2
python
{ "resource": "" }
q33771
bbox_vert_aligned_center
train
def bbox_vert_aligned_center(box1, box2): """ Returns true if the center of both boxes is within 5 pts """ if not (box1 and box2): return False return abs(((box1.right + box1.left) / 2.0) - ((box2.right + box2.left) / 2.0)) <= 5
python
{ "resource": "" }
q33772
_NgramMatcher._is_subspan
train
def _is_subspan(self, m, span): """ Tests if mention m is subspan of span, where span is defined specific to mention type. """ return ( m.sentence.id == span[0] and m.char_start >= span[1] and m.char_end <= span[2] )
python
{ "resource": "" }
q33773
_NgramMatcher._get_span
train
def _get_span(self, m): """ Gets a tuple that identifies a span for the specific mention class that m belongs to. """ return (m.sentence.id, m.char_start, m.char_end)
python
{ "resource": "" }
q33774
_FigureMatcher._is_subspan
train
def _is_subspan(self, m, span): """Tests if mention m does exist""" return m.figure.document.id == span[0] and m.figure.position == span[1]
python
{ "resource": "" }
q33775
_FigureMatcher._get_span
train
def _get_span(self, m): """ Gets a tuple that identifies a figure for the specific mention class that m belongs to. """ return (m.figure.document.id, m.figure.position)
python
{ "resource": "" }
q33776
candidate_subclass
train
def candidate_subclass( class_name, args, table_name=None, cardinality=None, values=None ): """ Creates and returns a Candidate subclass with provided argument names, which are Context type. Creates the table in DB if does not exist yet. Import using: .. code-block:: python from fondu...
python
{ "resource": "" }
q33777
CandidateExtractor.apply
train
def apply(self, docs, split=0, clear=True, parallelism=None, progress_bar=True): """Run the CandidateExtractor. :Example: To extract candidates from a set of training documents using 4 cores:: candidate_extractor.apply(train_docs, split=0, parallelism=4) :param doc...
python
{ "resource": "" }
q33778
CandidateExtractor.clear
train
def clear(self, split): """Delete Candidates of each class initialized with the CandidateExtractor from given split the database. :param split: Which split to clear. :type split: int """ for candidate_class in self.candidate_classes: logger.info( ...
python
{ "resource": "" }
q33779
CandidateExtractor.clear_all
train
def clear_all(self, split): """Delete ALL Candidates from given split the database. :param split: Which split to clear. :type split: int """ logger.info("Clearing ALL Candidates.") self.session.query(Candidate).filter(Candidate.split == split).delete( synchro...
python
{ "resource": "" }
q33780
CandidateExtractor.get_candidates
train
def get_candidates(self, docs=None, split=0, sort=False): """Return a list of lists of the candidates associated with this extractor. Each list of the return will contain the candidates for one of the candidate classes associated with the CandidateExtractor. :param docs: If provided, r...
python
{ "resource": "" }
q33781
SparseLinear.reset_parameters
train
def reset_parameters(self): """Reinitiate the weight parameters. """ stdv = 1.0 / math.sqrt(self.num_features) self.weight.weight.data.uniform_(-stdv, stdv) if self.bias is not None: self.bias.data.uniform_(-stdv, stdv) if self.padding_idx is not None: ...
python
{ "resource": "" }
q33782
save_marginals
train
def save_marginals(session, X, marginals, training=True): """Save marginal probabilities for a set of Candidates to db. :param X: A list of arbitrary objects with candidate ids accessible via a .id attrib :param marginals: A dense M x K matrix of marginal probabilities, where K is the cardi...
python
{ "resource": "" }
q33783
compile_entity_feature_generator
train
def compile_entity_feature_generator(): """ Given optional arguments, returns a generator function which accepts an xml root and a list of indexes for a mention, and will generate relation features for this entity. """ BASIC_ATTRIBS_REL = ["lemma", "dep_label"] m = Mention(0) # Basic ...
python
{ "resource": "" }
q33784
get_ddlib_feats
train
def get_ddlib_feats(span, context, idxs): """ Minimalist port of generic mention features from ddlib """ if span.stable_id not in unary_ddlib_feats: unary_ddlib_feats[span.stable_id] = set() for seq_feat in _get_seq_features(context, idxs): unary_ddlib_feats[span.stable_id]...
python
{ "resource": "" }
q33785
_get_cand_values
train
def _get_cand_values(candidate, key_table): """Get the corresponding values for the key_table.""" # NOTE: Import just before checking to avoid circular imports. from fonduer.features.models import FeatureKey from fonduer.supervision.models import GoldLabelKey, LabelKey if key_table == FeatureKey: ...
python
{ "resource": "" }
q33786
_batch_postgres_query
train
def _batch_postgres_query(table, records): """Break the list into chunks that can be processed as a single statement. Postgres query cannot be too long or it will fail. See: https://dba.stackexchange.com/questions/131399/is-there-a-maximum- length-constraint-for-a-postgres-query :param records: T...
python
{ "resource": "" }
q33787
get_sparse_matrix_keys
train
def get_sparse_matrix_keys(session, key_table): """Return a list of keys for the sparse matrix.""" return session.query(key_table).order_by(key_table.name).all()
python
{ "resource": "" }
q33788
batch_upsert_records
train
def batch_upsert_records(session, table, records): """Batch upsert records into postgresql database.""" if not records: return for record_batch in _batch_postgres_query(table, records): stmt = insert(table.__table__) stmt = stmt.on_conflict_do_update( constraint=table.__t...
python
{ "resource": "" }
q33789
get_docs_from_split
train
def get_docs_from_split(session, candidate_classes, split): """Return a list of documents that contain the candidates in the split.""" # Only grab the docs containing candidates from the given split. sub_query = session.query(Candidate.id).filter(Candidate.split == split).subquery() split_docs = set() ...
python
{ "resource": "" }
q33790
get_mapping
train
def get_mapping(session, table, candidates, generator, key_map): """Generate map of keys and values for the candidate from the generator. :param session: The database session. :param table: The table we will be inserting into (i.e. Feature or Label). :param candidates: The candidates to get mappings fo...
python
{ "resource": "" }
q33791
get_cands_list_from_split
train
def get_cands_list_from_split(session, candidate_classes, doc, split): """Return the list of list of candidates from this document based on the split.""" cands = [] if split == ALL_SPLITS: # Get cands from all splits for candidate_class in candidate_classes: cands.append( ...
python
{ "resource": "" }
q33792
drop_all_keys
train
def drop_all_keys(session, key_table, candidate_classes): """Bulk drop annotation keys for all the candidate_classes in the table. Rather than directly dropping the keys, this removes the candidate_classes specified for the given keys only. If all candidate_classes are removed for a key, the key is dro...
python
{ "resource": "" }
q33793
drop_keys
train
def drop_keys(session, key_table, keys): """Bulk drop annotation keys to the specified table. Rather than directly dropping the keys, this removes the candidate_classes specified for the given keys only. If all candidate_classes are removed for a key, the key is dropped. :param key_table: The sqla...
python
{ "resource": "" }
q33794
upsert_keys
train
def upsert_keys(session, key_table, keys): """Bulk add annotation keys to the specified table. :param key_table: The sqlalchemy class to insert into. :param keys: A map of {name: [candidate_classes]}. """ # Do nothing if empty if not keys: return for key_batch in _batch_postgres_qu...
python
{ "resource": "" }
q33795
Labeler.update
train
def update(self, docs=None, split=0, lfs=None, parallelism=None, progress_bar=True): """Update the labels of the specified candidates based on the provided LFs. :param docs: If provided, apply the updated LFs to all the candidates in these documents. :param split: If docs is None, a...
python
{ "resource": "" }
q33796
Labeler.apply
train
def apply( self, docs=None, split=0, train=False, lfs=None, clear=True, parallelism=None, progress_bar=True, ): """Apply the labels of the specified candidates based on the provided LFs. :param docs: If provided, apply the LFs to all t...
python
{ "resource": "" }
q33797
Labeler.clear
train
def clear(self, train, split, lfs=None): """Delete Labels of each class from the database. :param train: Whether or not to clear the LabelKeys. :type train: bool :param split: Which split of candidates to clear labels from. :type split: int :param lfs: This parameter is ...
python
{ "resource": "" }
q33798
Labeler.clear_all
train
def clear_all(self): """Delete all Labels.""" logger.info("Clearing ALL Labels and LabelKeys.") self.session.query(Label).delete(synchronize_session="fetch") self.session.query(LabelKey).delete(synchronize_session="fetch")
python
{ "resource": "" }
q33799
LabelerUDF._f_gen
train
def _f_gen(self, c): """Convert lfs into a generator of id, name, and labels. In particular, catch verbose values and convert to integer ones. """ lf_idx = self.candidate_classes.index(c.__class__) labels = lambda c: [(c.id, lf.__name__, lf(c)) for lf in self.lfs[lf_idx]] ...
python
{ "resource": "" }