INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return an error message for use in exceptions thrown by subclasses.
def err_msg(self, instance, value): """Return an error message for use in exceptions thrown by subclasses. """ if not hasattr(self, "name"): # err_msg will be called by the composed descriptor return "" return ( "Attempted to set the {f_type} ...
Return True if the last exception was thrown by a Descriptor instance.
def exc_thrown_by_descriptor(): """Return True if the last exception was thrown by a Descriptor instance. """ traceback = sys.exc_info()[2] tb_locals = traceback.tb_frame.f_locals # relying on naming convention to get the object that threw # the exception ...
This method will be called to set Series data
def _set_data(self): """ This method will be called to set Series data """ if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False): _x = XVariable() _y = YVariable() _x.contribute_to_class(self, 'X', self.d...
will get the axis mode for the current series
def _get_axis_mode(self, axis): "will get the axis mode for the current series" if all([isinstance(getattr(s, axis), TimeVariable) for s in self._series]): return 'time' return None
sets the graph ploting options
def _set_options(self): "sets the graph ploting options" # this is aweful # FIXME: Axis options should be passed completly by a GraphOption if 'xaxis' in self._options.keys(): self._options['xaxis'].update( {'mode' : self._get_axis_mode(XAxis._var_name...
Create an __init__ method that sets all the attributes necessary for the function the Descriptor invokes to check the value.
def create_init(attrs): """Create an __init__ method that sets all the attributes necessary for the function the Descriptor invokes to check the value. """ args = ", ".join(attrs) vals = ", ".join(['getattr(self, "{}")'.format(attr) for attr in attrs]) attr_lines = "\n ".join( ["...
Create the __set__ method for the descriptor.
def create_setter(func, attrs): """Create the __set__ method for the descriptor.""" def _set(self, instance, value, name=None): args = [getattr(self, attr) for attr in attrs] if not func(value, *args): raise ValueError(self.err_msg(instance, value)) return _set
Turn a funcs list element into a class object.
def make_class(clsname, func, attrs): """Turn a funcs list element into a class object.""" clsdict = {"__set__": create_setter(func, attrs)} if len(attrs) > 0: clsdict["__init__"] = create_init(attrs) clsobj = type(str(clsname), (Descriptor, ), clsdict) clsobj.__doc__ = docstrings.get(clsnam...
Cycles through notifications with latest results from data feeds.
def cycle(self): """ Cycles through notifications with latest results from data feeds. """ messages = self.poll_datafeeds() notifications = self.process_notifications(messages) self.draw_notifications(notifications)
Convert value to a numeric value or raise a ValueError if that isn t possible.
def try_convert(value): """Convert value to a numeric value or raise a ValueError if that isn't possible. """ convertible = ForceNumeric.is_convertible(value) if not convertible or isinstance(value, bool): raise ValueError if isinstance(str(value), str): ...
Convert str_value to an int or a float depending on the numeric value represented by str_value.
def str_to_num(str_value): """Convert str_value to an int or a float, depending on the numeric value represented by str_value. """ str_value = str(str_value) try: return int(str_value) except ValueError: return float(str_value)
Tag to plot graphs into the template
def plot(parser, token): """ Tag to plot graphs into the template """ tokens = token.split_contents() tokens.pop(0) graph = tokens.pop(0) attrs = dict([token.split("=") for token in tokens]) if 'id' not in attrs.keys(): attrs['id'] = ''.join([chr(choice(range(65, 90))) for i i...
Try really really hard to get a Unicode copy of a string.
def force_unicode(raw): '''Try really really hard to get a Unicode copy of a string. First try :class:`BeautifulSoup.UnicodeDammit` to try to force to Unicode; if that fails, assume UTF-8 encoding, and ignore all errors. :param str raw: string to coerce :return: Unicode approximation of `raw` ...
Get a clean text representation of presumed HTML.
def make_clean_html(raw, stream_item=None, encoding=None): '''Get a clean text representation of presumed HTML. Treat `raw` as though it is HTML, even if we have no idea what it really is, and attempt to get a properly formatted HTML document with all HTML-escaped characters converted to their unicode....
Takes a utf - 8 - encoded string of HTML as input and returns a new HTML string with fixed quoting and close tags which generally should not break any of the offsets and makes it easier for functions like: func: streamcorpus_pipeline. offsets. char_offsets_to_xpaths to operate without failures.
def uniform_html(html): '''Takes a utf-8-encoded string of HTML as input and returns a new HTML string with fixed quoting and close tags, which generally should not break any of the offsets and makes it easier for functions like :func:`streamcorpus_pipeline.offsets.char_offsets_to_xpaths` to ope...
This implements the MIME - type matching logic for deciding whether to run make_clean_html
def is_matching_mime_type(self, mime_type): '''This implements the MIME-type matching logic for deciding whether to run `make_clean_html` ''' if len(self.include_mime_types) == 0: return True if mime_type is None: return False mime_type = mime_typ...
extract a lower - case no - slashes domain name from a raw string that might be a URL
def domain_name_cleanse(raw_string): '''extract a lower-case, no-slashes domain name from a raw string that might be a URL ''' try: parts = urlparse(raw_string) domain = parts.netloc.split(':')[0] except: domain = '' if not domain: domain = raw_string if not d...
returns a list of strings created by splitting the domain on. and successively cutting off the left most portion
def domain_name_left_cuts(domain): '''returns a list of strings created by splitting the domain on '.' and successively cutting off the left most portion ''' cuts = [] if domain: parts = domain.split('.') for i in range(len(parts)): cuts.append( '.'.join(parts[i:])) r...
Get a Murmur hash and a normalized token.
def make_hash_kw(self, tok): '''Get a Murmur hash and a normalized token. `tok` may be a :class:`unicode` string or a UTF-8-encoded byte string. :data:`DOCUMENT_HASH_KEY`, hash value 0, is reserved for the document count, and this function remaps that value. :param tok...
Collect all of the words to be indexed from a stream item.
def collect_words(self, si): '''Collect all of the words to be indexed from a stream item. This scans `si` for all of the configured tagger IDs. It collects all of the token values (the :attr:`streamcorpus.Token.token`) and returns a :class:`collections.Counter` of them. ...
Record index records for a single document.
def index(self, si): '''Record index records for a single document. Which indexes this creates depends on the parameters to the constructor. This records all of the requested indexes for a single document. ''' if not si.body.clean_visible: logger.warn('stre...
Get strings that correspond to some hash.
def invert_hash(self, tok_hash): '''Get strings that correspond to some hash. No string will correspond to :data:`DOCUMENT_HASH_KEY`; use :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead. :param int tok_hash: Murmur hash to query :return: list of :class:`unicode` strings ...
Get document frequencies for a list of hashes.
def document_frequencies(self, hashes): '''Get document frequencies for a list of hashes. This will return all zeros unless the index was written with `hash_frequencies` set. If :data:`DOCUMENT_HASH_KEY` is included in `hashes`, that value will be returned with the total number...
Get stream IDs for a single hash.
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a ...
Get stream IDs and term frequencies for a single hash.
def lookup_tf(self, h): '''Get stream IDs and term frequencies for a single hash. This yields pairs of strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item` and the corresponding term frequency. ..see:: :meth:`lookup` ''' ...
Given a spinn3r feed produce a sequence of valid StreamItems.
def _make_stream_items(f): """Given a spinn3r feed, produce a sequence of valid StreamItems. Because of goopy Python interactions, you probably need to call this and re-yield its results, as >>> with open(filename, 'rb') as f: ... for si in _make_stream_items(f): ... yield si """ ...
Given a single spinn3r feed entry produce a single StreamItem.
def _make_stream_item(entry): """Given a single spinn3r feed entry, produce a single StreamItem. Returns 'None' if a complete item can't be constructed. """ # get standard metadata, assuming it's present... if not hasattr(entry, 'permalink_entry'): return None pe = entry.permalink_entr...
Create a ContentItem from a node in the spinn3r data tree.
def _make_content_item(node, mime_type=None, alternate_data=None): """Create a ContentItem from a node in the spinn3r data tree. The ContentItem is created with raw data set to ``node.data``, decompressed if the node's encoding is 'zlib', and UTF-8 normalized, with a MIME type from ``node.mime_type``. ...
Read ( up to ) n bytes from the underlying file. If any bytes have been pushed in with _unread () those are returned first.
def _read(self, n): """Read (up to) 'n' bytes from the underlying file. If any bytes have been pushed in with _unread() those are returned first.""" if n <= len(self._prefix): # the read can be fulfilled entirely from the prefix result = self._prefix[:n] self...
Read exactly a varint out of the underlying file.
def _read_varint(self): """Read exactly a varint out of the underlying file.""" buf = self._read(8) (n, l) = _DecodeVarint(buf, 0) self._unread(buf[l:]) return n
Read some protobuf - encoded object stored in a single block out of the file.
def _read_a(self, cls): """Read some protobuf-encoded object stored in a single block out of the file.""" o = cls() o.ParseFromString(self._read_block()) return o
Parse the: class: from_kvlayer input string.
def parse_keys_and_ranges(i_str, keyfunc, rangefunc): '''Parse the :class:`from_kvlayer` input string. This accepts two formats. In the textual format, it accepts any number of stream IDs in timestamp-docid format, separated by ``,`` or ``;``, and processes those as individual stream IDs. In the ...
Retrieve a: class: streamcorpus. StreamItem from: mod: kvlayer.
def get_kvlayer_stream_item(client, stream_id): '''Retrieve a :class:`streamcorpus.StreamItem` from :mod:`kvlayer`. This function requires that `client` already be set up properly:: client = kvlayer.client() client.setup_namespace(STREAM_ITEM_TABLE_DEFS, STREAM_I...
Construct a tuple ( begin end ) of one - tuple kvlayer keys from a hexdigest doc_id.
def make_doc_id_range(doc_id): '''Construct a tuple(begin, end) of one-tuple kvlayer keys from a hexdigest doc_id. ''' assert len(doc_id) == 32, 'expecting 32 hex string, not: %r' % doc_id bin_docid = base64.b16decode(doc_id.upper()) doc_id_range = ((bin_docid,), (bin_docid,)) return doc_id...
Retrieve: class: streamcorpus. StreamItem s from: mod: kvlayer.
def get_kvlayer_stream_item_by_doc_id(client, doc_id): '''Retrieve :class:`streamcorpus.StreamItem`s from :mod:`kvlayer`. Namely, it returns an iterator over all documents with the given docid. The docid should be an md5 hash of the document's abs_url. :param client: kvlayer client object :type cl...
Retrieve stream ids from: mod: kvlayer.
def get_kvlayer_stream_ids_by_doc_id(client, doc_id): '''Retrieve stream ids from :mod:`kvlayer`. Namely, it returns an iterator over all stream ids with the given docid. The docid should be an md5 hash of the document's abs_url. :param client: kvlayer client object :type client: :class:`kvlayer.A...
Return packed bytes representation of StreamItem kvlayer key. The result is 20 bytes 16 of md5 hash 4 of int timestamp.
def serialize_si_key(si_key): ''' Return packed bytes representation of StreamItem kvlayer key. The result is 20 bytes, 16 of md5 hash, 4 of int timestamp. ''' if len(si_key[0]) != 16: raise ValueError('bad StreamItem key, expected 16 byte ' 'md5 hash binary digest, ...
extract the parts of a StreamItem that go into a kvlayer key convert StreamItem to blob for storage.
def streamitem_to_key_data(si): ''' extract the parts of a StreamItem that go into a kvlayer key, convert StreamItem to blob for storage. return (kvlayer key tuple), data blob ''' key = key_for_stream_item(si) data = streamcorpus.serialize(si) errors, data = streamcorpus.compress_and_en...
Change working directory and restore the previous on exit
def working_directory(path): """Change working directory and restore the previous on exit""" prev_dir = os.getcwd() os.chdir(str(path)) try: yield finally: os.chdir(prev_dir)
Removes the prefix if it s there otherwise returns input string unchanged. If strict is True also ensures the prefix was present
def strip_prefix(s, prefix, strict=False): """Removes the prefix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the prefix was present""" if s.startswith(prefix): return s[len(prefix) :] elif strict: raise WimpyError("string doesn't start with p...
Removes the suffix if it s there otherwise returns input string unchanged. If strict is True also ensures the suffix was present
def strip_suffix(s, suffix, strict=False): """Removes the suffix, if it's there, otherwise returns input string unchanged. If strict is True, also ensures the suffix was present""" if s.endswith(suffix): return s[: len(s) - len(suffix)] elif strict: raise WimpyError("string doesn't end w...
Are all the elements of needle contained in haystack and in the same order? There may be other elements interspersed throughout
def is_subsequence(needle, haystack): """Are all the elements of needle contained in haystack, and in the same order? There may be other elements interspersed throughout""" it = iter(haystack) for element in needle: if element not in it: return False return True
Return an Ice application with a default home page.
def cube(): """Return an Ice application with a default home page. Create :class:`Ice` object, add a route to return the default page when a client requests the server root, i.e. /, using HTTP GET method, add an error handler to return HTTP error pages when an error occurs and return this object. T...
Run the application using a simple WSGI server.
def run(self, host='127.0.0.1', port=8080): """Run the application using a simple WSGI server. Arguments: host (str, optional): Host on which to listen. port (int, optional): Port number on which to listen. """ from wsgiref import simple_server self._server =...
Stop the simple WSGI server running the appliation.
def exit(self): """Stop the simple WSGI server running the appliation.""" if self._server is not None: self._server.shutdown() self._server.server_close() self._server = None
Decorator to add route for a request with any HTTP method.
def route(self, method, pattern): """Decorator to add route for a request with any HTTP method. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. pattern (str): Routing pattern the path must match. Returns: function: Decorator function to add route. ...
Decorator to add a callback that generates error page.
def error(self, status=None): """Decorator to add a callback that generates error page. The *status* parameter specifies the HTTP response status code for which the decorated callback should be invoked. If the *status* argument is not specified, then the decorated callable is co...
Send content of a static file as response.
def static(self, root, path, media_type=None, charset='UTF-8'): """Send content of a static file as response. The path to the document root directory should be specified as the root argument. This is very important to prevent directory traversal attack. This method guarantees that only ...
Send content as attachment ( downloadable file ).
def download(self, content, filename=None, media_type=None, charset='UTF-8'): """Send content as attachment (downloadable file). The *content* is sent after setting Content-Disposition header such that the client prompts the user to save the content locally as a file. A...
Return an error page for the current response status.
def _get_error_page_callback(self): """Return an error page for the current response status.""" if self.response.status in self._error_handlers: return self._error_handlers[self.response.status] elif None in self._error_handlers: return self._error_handlers[None] ...
Add a route.
def add(self, method, pattern, callback): """Add a route. Arguments: method (str): HTTP method, e.g. GET, POST, etc. pattern (str): Pattern that request paths must match. callback (str): Route handler that is invoked when a request path matches the *pattern*. ...
Check if there is at least one handler for * method *.
def contains_method(self, method): """Check if there is at least one handler for *method*. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. Returns: ``True`` if there is at least one route defined for *method*, ``False`` otherwise """ ...
Resolve a request to a route handler.
def resolve(self, method, path): """Resolve a request to a route handler. Arguments: method (str): HTTP method, e.g. GET, POST, etc. (type: str) path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) ...
Resolve a request to a wildcard or regex route handler.
def _resolve_non_literal_route(self, method, path): """Resolve a request to a wildcard or regex route handler. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. path (str): Request path Returns: tuple or None: A tuple of three items: 1. ...
Return a normalized form of the pattern.
def _normalize_pattern(pattern): """Return a normalized form of the pattern. Normalize the pattern by removing pattern type prefix if it exists in the pattern. Then return the pattern type and the pattern as a tuple of two strings. Arguments: pattern (str): Route patt...
Return route handler with arguments if path matches this route.
def match(self, path): """Return route handler with arguments if path matches this route. Arguments: path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) 3. K...
Return route handler with arguments if path matches this route.
def match(self, path): """Return route handler with arguments if path matches this route. Arguments: path (str): Request path Returns: tuple or None: A tuple of three items: 1. Route handler (callable) 2. Positional arguments (list) 3. K...
Return the HTTP response body.
def response(self): """Return the HTTP response body. Returns: bytes: HTTP response body as a sequence of bytes """ if isinstance(self.body, bytes): out = self.body elif isinstance(self.body, str): out = self.body.encode(self.charset) el...
Add an HTTP header to response object.
def add_header(self, name, value): """Add an HTTP header to response object. Arguments: name (str): HTTP header field name value (str): HTTP header field value """ if value is not None: self._headers.append((name, value))
Add a Set - Cookie header to response object.
def set_cookie(self, name, value, attrs={}): """Add a Set-Cookie header to response object. For a description about cookie attribute values, see https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel. Arguments: name (str): Name of the cookie value ...
Return the HTTP response status line.
def status_line(self): """Return the HTTP response status line. The status line is determined from :attr:`status` code. For example, if the status code is 200, then '200 OK' is returned. Returns: str: Status line """ return (str(self.status) + ' ' + ...
Return the value of Content - Type header field.
def content_type(self): """Return the value of Content-Type header field. The value for the Content-Type header field is determined from the :attr:`media_type` and :attr:`charset` data attributes. Returns: str: Value of Content-Type header field """ if (self.m...
Return the list of all values for the specified key.
def getall(self, key, default=[]): """Return the list of all values for the specified key. Arguments: key (object): Key default (list): Default value to return if the key does not exist, defaults to ``[]``, i.e. an empty list. Returns: list: List of al...
remove all files and directories below path including path itself ; works even when shutil. rmtree fails because of read - only files in NFS and Windows. Follows symlinks.
def rmtree(path, use_shutil=True, followlinks=False, retries=10): '''remove all files and directories below path, including path itself; works even when shutil.rmtree fails because of read-only files in NFS and Windows. Follows symlinks. `use_shutil` defaults to True; useful for testing `followli...
return list of open files for current process
def get_open_fds(verbose=False): '''return list of open files for current process .. warning: will only work on UNIX-like os-es. ''' pid = os.getpid() procs = subprocess.check_output( [ "lsof", '-w', '-Ff', "-p", str( pid ) ] ) if verbose: oprocs = subprocess.check_output( ...
returns a kba. pipeline transform function that generates file type stats from the stream_items that it sees. Currently these stats are just the first five non - whitespace characters.
def file_type_stats(config): ''' returns a kba.pipeline "transform" function that generates file type stats from the stream_items that it sees. Currently, these stats are just the first five non-whitespace characters. ''' ## make a closure around config def _file_type_stats(stream_item, con...
get a rejester. WorkUnit with KBA s3 path fetch it and save some counts about it.
def rejester_run(work_unit): '''get a rejester.WorkUnit with KBA s3 path, fetch it, and save some counts about it. ''' #fname = 'verify-chunks-%d-%d' % (os.getpid(), time.time()) fname = work_unit.key.strip().split('/')[-1] output_dir_path = work_unit.data.get('output_dir_path', '/mn...
attempt a fetch and iteration over a work_unit. key path in s3
def attempt_fetch(work_unit, fpath): '''attempt a fetch and iteration over a work_unit.key path in s3 ''' url = 'http://s3.amazonaws.com/aws-publicdatasets/' + work_unit.key.strip() ## cheapest way to iterate over the corpus is a few stages of ## streamed child processes. Note that stderr nee...
Return a list of non - empty lines from file_path.
def get_file_lines(file_name): """Return a list of non-empty lines from `file_path`.""" file_path = path.join(path.dirname(path.abspath(__file__)), file_name) with open(file_path) as file_obj: return [line for line in file_obj.read().splitlines() if line]
Return a describer tuple in the form ( name position ) where position is either prefix or suffix.
def get_describers(): """ Return a describer tuple in the form `(name, position)`, where position is either 'prefix' or 'suffix'. """ adjectives = map(lambda x: (x, 'prefix'), get_file_lines('adjectives.txt')) animal_nouns = map(lambda x: (x, 'suffix'), get_file_lines('nouns.txt')) return li...
Return an ordered 2 - tuple containing a species and a describer.
def _random_adjspecies_pair(): """Return an ordered 2-tuple containing a species and a describer.""" describer, desc_position = random_describer() if desc_position == 'prefix': return (describer, random_species()) elif desc_position == 'suffix': return (random_species(), describer)
Return an ordered 2 - tuple containing a species and a describer. The letter - count of the pair is guarantee to not exceed maxlen if it is given. If prevent_stutter is True the last letter of the first item of the pair will be different from the first letter of the second item.
def random_adjspecies_pair(maxlen=None, prevent_stutter=True): """ Return an ordered 2-tuple containing a species and a describer. The letter-count of the pair is guarantee to not exceed `maxlen` if it is given. If `prevent_stutter` is True, the last letter of the first item of the pair will be diff...
Return a random adjective/ species separated by sep. The keyword arguments maxlen and prevent_stutter are the same as for random_adjspecies_pair but note that the maximum length argument is not affected by the separator.
def random_adjspecies(sep='', maxlen=8, prevent_stutter=True): """ Return a random adjective/species, separated by `sep`. The keyword arguments `maxlen` and `prevent_stutter` are the same as for `random_adjspecies_pair`, but note that the maximum length argument is not affected by the separator. ...
Morphological analysis for Japanese.
def morph(ctx, app_id, sentence_file, json_flag, sentence, info_filter, pos_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode, unicode) -> None # NOQA """ Morphological analysis for Japanese.""" app_id = clean_app_id(app_id) sentence = clean_senten...
Scoring the similarity of two words.
def similarity(ctx, app_id, json_flag, query_pair, request_id): # type: (Context, unicode, bool, List[unicode], unicode) -> None """ Scoring the similarity of two words. """ app_id = clean_app_id(app_id) api = GoolabsAPI(app_id) ret = api.similarity( query_pair=query_pair, request_...
Convert the Japanese to Hiragana or Katakana.
def hiragana(ctx, app_id, sentence_file, json_flag, sentence, output_type, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Convert the Japanese to Hiragana or Katakana. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sen...
Extract unique representation from sentence.
def entity(ctx, app_id, sentence_file, json_flag, sentence, class_filter, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """ Extract unique representation from sentence. """ app_id = clean_app_id(app_id) sentence = clean_sentence(sentenc...
Summarize reviews into a short summary.
def shortsum(ctx, app_id, review_file, json_flag, review, length, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Summarize reviews into a short summary.""" app_id = clean_app_id(app_id) review_list = clean_review(review, review_file...
Extract keywords from an input document.
def keyword(ctx, app_id, body_file, json_flag, title, body, max_num, forcus, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, int, unicode, unicode) -> None # NOQA """Extract "keywords" from an input document. """ app_id = clean_app_id(app_id) body = clean_body(...
Extract expression expressing date and time and normalize its value
def chrono(ctx, app_id, sentence_file, json_flag, sentence, doc_time, request_id): # type: (Context, unicode, Optional[IO], bool, unicode, unicode, unicode) -> None # NOQA """Extract expression expressing date and time and normalize its value """ app_id = clean_app_id(app_id) sentence = cle...
Create a pipeline stage.
def create(self, stage, scp_config, config=None): '''Create a pipeline stage. Instantiates `stage` with `config`. This essentially translates to ``stage(config)``, except that two keys from `scp_config` are injected into the configuration: ``tmp_dir_path`` is an execution-speci...
Create a list of indirect stages.
def _init_stages(self, config, name): '''Create a list of indirect stages. `name` should be the name of a config item that holds a list of names of stages, for instance, ``writers``. This looks up the names of those stages, then creates and returns the corresponding list of sta...
Create stages that are used for the pipeline.
def _init_all_stages(self, config): '''Create stages that are used for the pipeline. :param dict config: `streamcorpus_pipeline` configuration :return: tuple of (reader, incremental transforms, batch transforms, post-batch incremental transforms, writers, temporary directory...
Process a: class: coordinate. WorkUnit.
def _process_task(self, work_unit): '''Process a :class:`coordinate.WorkUnit`. The work unit's key is taken as the input file name. The data should have ``start_count`` and ``start_chunk_time`` values, which are passed on to :meth:`run`. :param work_unit: work unit to process ...
Run the pipeline.
def run(self, i_str, start_count=0, start_chunk_time=None): '''Run the pipeline. This runs all of the steps described in the pipeline constructor, reading from some input and writing to some output. :param str i_str: name of the input file, or other reader-specific descriptio...
for the current output chunk ( which should be open ): 1. run batch transforms 2. run post - batch incremental transforms 3. run writers to load - out the data to files or other storage return list of paths that writers wrote to
def _process_output_chunk(self, start_count, next_idx, sources, i_str, t_path): ''' for the current output chunk (which should be open): 1. run batch transforms 2. run post-batch incremental transforms 3. run 'writers' to load-out the data to f...
Run all of the writers over some intermediate chunk.
def _run_writers(self, start_count, next_idx, sources, i_str, t_path): '''Run all of the writers over some intermediate chunk. :param int start_count: index of the first item :param int next_idx: index of the next item (after the last item in this chunk) :param list sources: s...
Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self. t_chunk Returns transformed item or None.
def _run_incremental_transforms(self, si, transforms): ''' Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None. ''' ## operate each transform on this one Strea...
takes a chunk blob and obtains the date_hour md5 num
def get_name_info(chunk_path, assert_one_date_hour=False, i_str=None, chunk_type=Chunk): ''' takes a chunk blob and obtains the date_hour, md5, num makes fields: i_str input_fname input_md5 - parsed from input filename if it contains '-%(md5)s-' md5 num epoch_ticks...
Replace the top - level pipeline configurable object.
def replace_config(config, name): '''Replace the top-level pipeline configurable object. This investigates a number of sources, including `external_stages_path` and `external_stages_modules` configuration and `streamcorpus_pipeline.stages` entry points, and uses these to find the actual :data:`sub_...
Make a WSGI app that has all the HTTPie pieces baked in.
def make_app(): """Make a WSGI app that has all the HTTPie pieces baked in.""" env = Environment() # STDIN is ignored because HTTPony runs a server that doesn't care. # Additionally, it is needed or else pytest blows up. args = parser.parse_args(args=['/', '--ignore-stdin'], env=env) args.output...
assemble in - doc coref chains by mapping equiv_id to tokens and their cleansed name strings
def make_chains_with_names(sentences): ''' assemble in-doc coref chains by mapping equiv_id to tokens and their cleansed name strings :param sentences: iterator over token generators :returns dict: keys are equiv_ids, values are tuple(concatentated name string, list of tokens) '...
For each name string in the target_mentions list searches through all chain_mentions looking for any cleansed Token. token that contains the name. Returns True only if all of the target_mention strings appeared as substrings of at least one cleansed Token. token. Otherwise returns False.
def ALL_mentions(target_mentions, chain_mentions): ''' For each name string in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains the name. Returns True only if all of the target_mention strings appeared as substrings of at least one cle...
For each name string ( potentially consisting of multiple tokens ) in the target_mentions list searches through all chain_mentions looking for any cleansed Token. token that contains all the tokens in the name. Returns True only if all of the target_mention strings appeared as substrings of at least one cleansed Token....
def ANY_MULTI_TOKEN_mentions(multi_token_target_mentions, chain_mentions): ''' For each name string (potentially consisting of multiple tokens) in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains all the tokens in the name. Returns Tru...
For each name string in the target_mentions list searches through all chain_mentions looking for any cleansed Token. token that contains the name. Returns True if any of the target_mention strings appeared as substrings of any cleansed Token. token. Otherwise returns False.
def ANY_mentions(target_mentions, chain_mentions): ''' For each name string in the target_mentions list, searches through all chain_mentions looking for any cleansed Token.token that contains the name. Returns True if any of the target_mention strings appeared as substrings of any cleansed Token.to...
Convert doc - level Rating object into a Label and add that Label to all Token in all coref chains identified by aligner_data [ chain_selector ]
def names_in_chains(stream_item, aligner_data): ''' Convert doc-level Rating object into a Label, and add that Label to all Token in all coref chains identified by aligner_data["chain_selector"] :param stream_item: document that has a doc-level Rating to translate into token-level Labels. :para...
iterate through all tokens looking for matches of cleansed tokens or token regexes skipping tokens left empty by cleansing and coping with Token objects that produce multiple space - separated strings when cleansed. Yields tokens that match.
def look_ahead_match(rating, tokens): '''iterate through all tokens looking for matches of cleansed tokens or token regexes, skipping tokens left empty by cleansing and coping with Token objects that produce multiple space-separated strings when cleansed. Yields tokens that match. ''' ## this ...
iterate through tokens looking for near - exact matches to strings in si. ratings... mentions
def multi_token_match(stream_item, aligner_data): ''' iterate through tokens looking for near-exact matches to strings in si.ratings...mentions ''' tagger_id = _get_tagger_id(stream_item, aligner_data) sentences = stream_item.body.sentences.get(tagger_id) if not sentences: return...
run tagger a child process to get XML output
def make_ner_file(self, clean_visible_path, ner_xml_path): '''run tagger a child process to get XML output''' if self.template is None: raise exceptions.NotImplementedError(''' Subclasses must specify a class property "template" that provides command string format for running a tagger. It s...
iterate through ner_xml_path to fuse with i_chunk into o_chunk
def align_chunk_with_ner(self, ner_xml_path, i_chunk, o_chunk): ''' iterate through ner_xml_path to fuse with i_chunk into o_chunk ''' ## prepare to iterate over the input chunk input_iter = i_chunk.__iter__() all_ner = xml.dom.minidom.parse(open(ner_xml_path)) ## this converts...