INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Initiate an XMPP connection over the transport.
def initiate(self, transport, to = None): """Initiate an XMPP connection over the `transport`. :Parameters: - `transport`: an XMPP transport instance - `to`: peer name """ with self.lock: self.initiator = True self.transport = transport ...
Receive an XMPP connection over the transport.
def receive(self, transport, myname): """Receive an XMPP connection over the `transport`. :Parameters: - `transport`: an XMPP transport instance - `myname`: local stream endpoint name. """ with self.lock: self.transport = transport transpo...
Set up stream element handlers.
def _setup_stream_element_handlers(self): """Set up stream element handlers. Scans the `handlers` list for `StreamFeatureHandler` instances and updates `_element_handlers` mapping with their methods decorated with @`stream_element_handler` """ # pylint: disable-msg=W0212...
Handle a stream event.
def event(self, event): # pylint: disable-msg=R0201 """Handle a stream event. Called when connection state is changed. Should not be called with self.lock acquired! """ event.stream = self logger.debug(u"Stream event: {0}".format(event)) self.settings["event_que...
Called when transport has been connected.
def transport_connected(self): """Called when transport has been connected. Send the stream head if initiator. """ with self.lock: if self.initiator: if self._output_state is None: self._initiate()
Process <stream: stream > ( stream start ) tag received from peer.
def stream_start(self, element): """Process <stream:stream> (stream start) tag received from peer. `lock` is acquired when this method is called. :Parameters: - `element`: root element (empty) created by the parser""" with self.lock: logger.debug("input document...
Process </ stream: stream > ( stream end ) tag received from peer.
def stream_end(self): """Process </stream:stream> (stream end) tag received from peer. """ logger.debug("Stream ended") with self.lock: self._input_state = "closed" self.transport.disconnect() self._output_state = "closed"
Send stream start tag.
def _send_stream_start(self, stream_id = None, stream_to = None): """Send stream start tag.""" if self._output_state in ("open", "closed"): raise StreamError("Stream start already sent") if not self.language: self.language = self.settings["language"] if stream_to:...
Same as send_stream_error but expects lock acquired.
def _send_stream_error(self, condition): """Same as `send_stream_error`, but expects `lock` acquired. """ if self._output_state is "closed": return if self._output_state in (None, "restart"): self._send_stream_start() element = StreamErrorElement(condition...
Restart the stream as needed after SASL and StartTLS negotiation.
def _restart_stream(self): """Restart the stream as needed after SASL and StartTLS negotiation.""" self._input_state = "restart" self._output_state = "restart" self.features = None self.transport.restart() if self.initiator: self._send_stream_start(self.stream...
Create the <features/ > element for the stream.
def _make_stream_features(self): """Create the <features/> element for the stream. [receving entity only] :returns: new <features/> element :returntype: :etree:`ElementTree.Element`""" features = ElementTree.Element(FEATURES_TAG) for handler in self._stream_feature_hand...
Send stream <features/ >.
def _send_stream_features(self): """Send stream <features/>. [receiving entity only]""" self.features = self._make_stream_features() self._write_element(self.features)
Same as send but assume lock is acquired.
def _send(self, stanza): """Same as `send` but assume `lock` is acquired.""" self.fix_out_stanza(stanza) element = stanza.as_xml() self._write_element(element)
Process first level element of the stream.
def _process_element(self, element): """Process first level element of the stream. The element may be stream error or features, StartTLS request/response, SASL request/response or a stanza. :Parameters: - `element`: XML element :Types: - `element`: :etre...
Handle stanza received from the stream.
def uplink_receive(self, stanza): """Handle stanza received from the stream.""" with self.lock: if self.stanza_route: self.stanza_route.uplink_receive(stanza) else: logger.debug(u"Stanza dropped (no route): {0!r}".format(stanza))
Process stream error element received.
def process_stream_error(self, error): """Process stream error element received. :Parameters: - `error`: error received :Types: - `error`: `StreamErrorElement` """ # pylint: disable-msg=R0201 logger.debug("Unhandled stream error: condition: {0} {...
Process incoming <stream: features/ > element.
def _got_features(self, features): """Process incoming <stream:features/> element. [initiating entity only] The received features node is available in `features`.""" self.features = features logger.debug("got features, passing to event handlers...") handled = self.event...
Mark the other side of the stream authenticated as peer
def set_peer_authenticated(self, peer, restart_stream = False): """Mark the other side of the stream authenticated as `peer` :Parameters: - `peer`: local JID just authenticated - `restart_stream`: `True` when stream should be restarted (needed after SASL authentica...
Mark stream authenticated as me.
def set_authenticated(self, me, restart_stream = False): """Mark stream authenticated as `me`. :Parameters: - `me`: local JID just authenticated - `restart_stream`: `True` when stream should be restarted (needed after SASL authentication) :Types: ...
Authentication properties of the stream.
def auth_properties(self): """Authentication properties of the stream. Derived from the transport with 'local-jid' and 'service-type' added. """ props = dict(self.settings["extra_auth_properties"]) if self.transport: props.update(self.transport.auth_properties) ...
Initiate an XMPP connection over the transport.
def initiate(self, transport, to = None): """Initiate an XMPP connection over the `transport`. :Parameters: - `transport`: an XMPP transport instance - `to`: peer name (defaults to own jid domain part) """ if to is None: to = JID(self.me.domain) ...
Receive an XMPP connection over the transport.
def receive(self, transport, myname = None): """Receive an XMPP connection over the `transport`. :Parameters: - `transport`: an XMPP transport instance - `myname`: local stream endpoint name (defaults to own jid domain part). """ if myname is None: ...
Fix outgoing stanza.
def fix_out_stanza(self, stanza): """Fix outgoing stanza. On a client clear the sender JID. On a server set the sender address to the own JID if the address is not set yet.""" StreamBase.fix_out_stanza(self, stanza) if self.initiator: if stanza.from_jid: ...
Fix an incoming stanza.
def fix_in_stanza(self, stanza): """Fix an incoming stanza. Ona server replace the sender address with authorized client JID.""" StreamBase.fix_in_stanza(self, stanza) if not self.initiator: if stanza.from_jid != self.peer: stanza.set_from(self.peer)
A loop iteration - check any scheduled events and I/ O available and run the handlers.
def loop_iteration(self, timeout = 60): """A loop iteration - check any scheduled events and I/O available and run the handlers. """ if self.check_events(): return 0 next_timeout, sources_handled = self._call_timeout_handlers() if self._quit: retur...
Prepare the I/ O handlers.
def _prepare_handlers(self): """Prepare the I/O handlers. :Return: (readable, writable, timeout) tuple. 'readable' is the list of readable handlers, 'writable' - the list of writable handlers, 'timeout' the suggested maximum timeout for this loop iteration or `None` ...
Initialize Register from an XML node.
def __from_xml(self, xmlnode): """Initialize `Register` from an XML node. :Parameters: - `xmlnode`: the jabber:x:register XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" self.__logger.debug("Converting jabber:iq:register element from XML") if xmln...
Complete the XML node with self content.
def complete_xml_element(self, xmlnode, doc): """Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the elemen...
Return Data Form for the Register object.
def get_form(self, form_type = "form"): """Return Data Form for the `Register` object. Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise. :Parameters: - `form_type`: If "form", then a form to fill-in should be returned. If "su...
Make Register object for submitting the registration form.
def submit_form(self, form): """Make `Register` object for submitting the registration form. Convert form data to legacy fields if `self.form` is `None`. :Parameters: - `form`: The form to submit. Its type doesn't have to be "submit" (a "submit" form will be created h...
Get jabber: x: delay elements from the stanza.
def get_delays(stanza): """Get jabber:x:delay elements from the stanza. :Parameters: - `stanza`: a, probably delayed, stanza. :Types: - `stanza`: `pyxmpp.stanza.Stanza` :return: list of delay tags sorted by the timestamp. :returntype: `list` of `Delay`""" delays=[] n=stanza...
Initialize Delay object from an XML node.
def from_xml(self,xmlnode): """Initialize Delay object from an XML node. :Parameters: - `xmlnode`: the jabber:x:delay XML element. :Types: - `xmlnode`: `libxml2.xmlNode`""" if xmlnode.type!="element": raise ValueError("XML node is not a jabber:x:delay...
Complete the XML node with self content.
def complete_xml_element(self, xmlnode, _unused): """Complete the XML node with `self` content. Should be overriden in classes derived from `StanzaPayloadObject`. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace,...
Parse the command - line arguments and run the bot.
def main(): """Parse the command-line arguments and run the bot.""" parser = argparse.ArgumentParser(description = 'XMPP echo bot', parents = [XMPPSettings.get_arg_parser()]) parser.add_argument('jid', metavar = 'JID', help = 'The ...
Echo every non - error <message/ > stanza. Add Re: to subject if any.
def handle_message(self, stanza): """Echo every non-error ``<message/>`` stanza. Add "Re: " to subject, if any. """ if stanza.subject: subject = u"Re: " + stanza.subject else: subject = None msg = Message(stanza_type = stanza.stanza_type, ...
When connecting start the next connection step and schedule next prepare call when connected return HandlerReady ()
def prepare(self): """When connecting start the next connection step and schedule next `prepare` call, when connected return `HandlerReady()` """ with self._lock: if self._socket: self._socket.listen(SOMAXCONN) self._socket.setblocking(False) ...
Accept any incoming connections.
def handle_read(self): """ Accept any incoming connections. """ with self._lock: logger.debug("handle_read()") if self._socket is None: return while True: try: sock, address = self._socket.accept() ...
Decode the stanza subelements.
def _decode_subelements(self): """Decode the stanza subelements.""" for child in self._element: if child.tag == self._show_tag: self._show = child.text elif child.tag == self._status_tag: self._status = child.text elif child.tag == self...
Return the XML stanza representation.
def as_xml(self): """Return the XML stanza representation. Always return an independent copy of the stanza XML representation, which can be freely modified without affecting the stanza. :returntype: :etree:`ElementTree.Element`""" result = Stanza.as_xml(self) if self._s...
Create a deep copy of the stanza.
def copy(self): """Create a deep copy of the stanza. :returntype: `Presence`""" result = Presence(None, self.from_jid, self.to_jid, self.stanza_type, self.stanza_id, self.error, self._return_path(), self._show, self._status...
Create accept response for the subscribe/ subscribed/ unsubscribe/ unsubscribed presence stanza.
def make_accept_response(self): """Create "accept" response for the "subscribe" / "subscribed" / "unsubscribe" / "unsubscribed" presence stanza. :return: new stanza. :returntype: `Presence` """ if self.stanza_type not in ("subscribe", "subscribed", ...
Create deny response for the subscribe/ subscribed/ unsubscribe/ unsubscribed presence stanza.
def make_deny_response(self): """Create "deny" response for the "subscribe" / "subscribed" / "unsubscribe" / "unsubscribed" presence stanza. :return: new presence stanza. :returntype: `Presence` """ if self.stanza_type not in ("subscribe", "subscribed", ...
Create error response for the any non - error presence stanza.
def make_error_response(self, cond): """Create error response for the any non-error presence stanza. :Parameters: - `cond`: error condition name, as defined in XMPP specification. :Types: - `cond`: `unicode` :return: new presence stanza. :returntype: `Pr...
Activate an plan in a CREATED state.
def activate(self): """ Activate an plan in a CREATED state. """ obj = self.find_paypal_object() if obj.state == enums.BillingPlanState.CREATED: success = obj.activate() if not success: raise PaypalApiError("Failed to activate plan: %r" % (obj.error)) # Resync the updated data to the database se...
Execute the PreparedBillingAgreement by creating and executing a matching BillingAgreement.
def execute(self): """ Execute the PreparedBillingAgreement by creating and executing a matching BillingAgreement. """ # Save the execution time first. # If execute() fails, executed_at will be set, with no executed_agreement set. self.executed_at = now() self.save() with transaction.atomic(): ret...
Decorator that registers a function as a webhook handler.
def webhook_handler(*event_types): """ Decorator that registers a function as a webhook handler. Usage examples: >>> # Hook a single event >>> @webhook_handler("payment.sale.completed") >>> def on_payment_received(event): >>> payment = event.get_resource() >>> print("Received payment:", payment) >>>...
Create validate and process a WebhookEventTrigger given a Django request object.
def from_request(cls, request, webhook_id=PAYPAL_WEBHOOK_ID): """ Create, validate and process a WebhookEventTrigger given a Django request object. The webhook_id parameter expects the ID of the Webhook that was triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required for Webhook verification. ...
Check and/ or create Django migrations.
def run(*args): """ Check and/or create Django migrations. If --check is present in the arguments then migrations are checked only. """ if not settings.configured: settings.configure(**DEFAULT_SETTINGS) django.setup() parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) if "--ch...
Check that the Paypal API keys are configured correctly
def check_paypal_api_key(app_configs=None, **kwargs): """Check that the Paypal API keys are configured correctly""" messages = [] mode = getattr(djpaypal_settings, "PAYPAL_MODE", None) if mode not in VALID_MODES: msg = "Invalid PAYPAL_MODE specified: {}.".format(repr(mode)) hint = "PAYPAL_MODE must be one of {...
Create the upstream applications.
async def _create_upstream_applications(self): """ Create the upstream applications. """ loop = asyncio.get_event_loop() for steam_name, ApplicationsCls in self.applications.items(): application = ApplicationsCls(self.scope) upstream_queue = asyncio.Queue(...
Send a message upstream to a de - multiplexed application.
async def send_upstream(self, message, stream_name=None): """ Send a message upstream to a de-multiplexed application. If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream steams. """ if stream_name is None: ...
Handle a downstream message coming from an upstream steam.
async def dispatch_downstream(self, message, steam_name): """ Handle a downstream message coming from an upstream steam. if there is not handling method set for this method type it will propagate the message further downstream. This is called as part of the co-routine of an upstream st...
Rout the message down the correct stream.
async def receive_json(self, content, **kwargs): """ Rout the message down the correct stream. """ # Check the frame looks good if isinstance(content, dict) and "stream" in content and "payload" in content: # Match it to a channel steam_name = content["str...
Handle the disconnect message.
async def websocket_disconnect(self, message): """ Handle the disconnect message. This is propagated to all upstream applications. """ # set this flag so as to ensure we don't send a downstream `websocket.close` message due to all # child applications closing. se...
default is to wait for the child applications to close.
async def disconnect(self, code): """ default is to wait for the child applications to close. """ try: await asyncio.wait( self.application_futures.values(), return_when=asyncio.ALL_COMPLETED, timeout=self.application_close_time...
Capture downstream websocket. send messages from the upstream applications.
async def websocket_send(self, message, stream_name): """ Capture downstream websocket.send messages from the upstream applications. """ text = message.get("text") # todo what to do on binary! json = await self.decode_json(text) data = { "stream": stre...
Intercept downstream websocket. accept message and thus allow this upsteam application to accept websocket frames.
async def websocket_accept(self, message, stream_name): """ Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket frames. """ is_first = not self.applications_accepting_frames self.applications_accepting_frames.add(str...
Handle downstream websocket. close message.
async def websocket_close(self, message, stream_name): """ Handle downstream `websocket.close` message. Will disconnect this upstream application from receiving any new frames. If there are not more upstream applications accepting messages it will then call `close`. """ ...
update interpolation data: param list ( float ) x_list: x values: param list ( float ) y_list: y values
def update(self, x_list=list(), y_list=list()): """ update interpolation data :param list(float) x_list: x values :param list(float) y_list: y values """ if not y_list: for x in x_list: if x in self.x_list: i = self.x_list.i...
finds interval of the interpolation in which x lies.: param x:: param intervals: the interpolation intervals: return:
def get_interval(x, intervals): """ finds interval of the interpolation in which x lies. :param x: :param intervals: the interpolation intervals :return: """ n = len(intervals) if n < 2: return intervals[0] n2 = n / 2 if x < int...
computes the coefficients for the single polynomials of the spline.
def set_interpolation_coefficients(self): """ computes the coefficients for the single polynomials of the spline. """ left_boundary_slope = 0 right_boundary_slope = 0 if isinstance(self.boundary_condition, tuple): left_boundary_slope = self.boundary_conditio...
creator method to build FxCurve
def cast(cls, fx_spot, domestic_curve=None, foreign_curve=None): """ creator method to build FxCurve :param float fx_spot: fx spot rate :param RateCurve domestic_curve: domestic discount curve :param RateCurve foreign_curve: foreign discount curve :return: """ ...
adds contents to FxShelf. If curve is FxCurve or FxDict spot should turn curve. currency into self. currency else spot should turn currency into self. currency by N in EUR * spot = N in USD for currency = EUR and self. currency = USD
def add(self, foreign_currency, foreign_curve=None, fx_spot=1.0): """ adds contents to FxShelf. If curve is FxCurve or FxDict, spot should turn curve.currency into self.currency, else spot should turn currency into self.currency by N in EUR * spot = N in USD for currency = EUR an...
_frange range like function for float inputs: param start:: type start:: param stop:: type stop:: param step:: type step:: return:: rtype:
def _frange(start, stop=None, step=None): """ _frange range like function for float inputs :param start: :type start: :param stop: :type stop: :param step: :type step: :return: :rtype: """ if stop is None: stop = start start = 0.0 if step is None: ...
interest_accrued: param valuation_date:: type valuation_date:: return:: rtype:
def interest_accrued(self, valuation_date): """ interest_accrued :param valuation_date: :type valuation_date: :return: :rtype: """ return sum([l.interest_accrued(valuation_date) for l in self.legs if hasattr(l, 'interest_accrued')])
Decorator to retry a function max_retries amount of times
def retry( exceptions=(Exception,), interval=0, max_retries=10, success=None, timeout=-1): """Decorator to retry a function 'max_retries' amount of times :param tuple exceptions: Exceptions to be caught for retries :param int interval: Interval between retries in seconds :param int max_...
Taken from https:// github. com/ tokland/ youtube - upload/ blob/ master/ youtube_upload/ main. py Get the first existing filename of relative_path seeking on prefixes directories.
def get_secrets(prefixes, relative_paths): """ Taken from https://github.com/tokland/youtube-upload/blob/master/youtube_upload/main.py Get the first existing filename of relative_path seeking on prefixes directories. """ try: return os.path.join(sys._MEIPASS, relative_paths[-1]) except E...
Button action event
def __button_action(self, data=None): """Button action event""" if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)): print("Missing one of the required fields (event name, player names, file name)") return self.__p1chars = [] ...
Generate a single A or B or C regex from a list of shell globs.
def multiglob_compile(globs, prefix=False): """Generate a single "A or B or C" regex from a list of shell globs. :param globs: Patterns to be processed by :mod:`fnmatch`. :type globs: iterable of :class:`~__builtins__.str` :param prefix: If ``True``, then :meth:`~re.RegexObject.match` will per...
Generate a hash from a potentially long file. Digesting will obey: const: CHUNK_SIZE to conserve memory.
def hashFile(handle, want_hex=False, limit=None, chunk_size=CHUNK_SIZE): """Generate a hash from a potentially long file. Digesting will obey :const:`CHUNK_SIZE` to conserve memory. :param handle: A file-like object or path to hash from. :param want_hex: If ``True``, returned hash will be hex-encoded. ...
Recursively walk a set of paths and return a listing of contained files.
def getPaths(roots, ignores=None): """ Recursively walk a set of paths and return a listing of contained files. :param roots: Relative or absolute paths to files or folders. :type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str` :param ignores: A list of :py:mod:`fnmatch` globs to ...
Subdivide groups of paths according to a function.
def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False, *args, **kwargs): """Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of pat...
Decorator to convert a function which takes a single value and returns a key into one which takes a list of values and returns a dict of key - group mappings.
def groupify(function): """Decorator to convert a function which takes a single value and returns a key into one which takes a list of values and returns a dict of key-group mappings. :param function: A function which takes a value and returns a hash key. :type function: ``function(value) -> key`` ...
Sort a file into a group based on on - disk size.
def sizeClassifier(path, min_size=DEFAULTS['min_size']): """Sort a file into a group based on on-disk size. :param paths: See :func:`fastdupes.groupify` :param min_size: Files smaller than this size (in bytes) will be ignored. :type min_size: :class:`__builtins__.int` :returns: See :func:`fastdup...
Byte - for - byte comparison on an arbitrary number of files in parallel.
def groupByContent(paths): """Byte-for-byte comparison on an arbitrary number of files in parallel. This operates by opening all files in parallel and comparing chunk-by-chunk. This has the following implications: - Reads the same total amount of data as hash comparison. - Performs a *lot*...
Group a list of file handles based on equality of the next chunk of data read from them.
def compareChunks(handles, chunk_size=CHUNK_SIZE): """Group a list of file handles based on equality of the next chunk of data read from them. :param handles: A list of open handles for file-like objects with otentially-identical contents. :param chunk_size: The amount of data to read from each...
Display a list of files and prompt for ones to be kept.
def pruneUI(dupeList, mainPos=1, mainLen=1): """Display a list of files and prompt for ones to be kept. The user may enter ``all`` or one or more numbers separated by spaces and/or commas. .. note:: It is impossible to accidentally choose to keep none of the displayed files. :param dupeLi...
High - level code to walk a set of paths and find duplicate groups.
def find_dupes(paths, exact=False, ignores=None, min_size=0): """High-level code to walk a set of paths and find duplicate groups. :param exact: Whether to compare file contents by hash or by reading chunks in parallel. :type exact: :class:`~__builtins__.bool` :param paths: See :meth...
Pretty - print the contents of: data: DEFAULTS
def print_defaults(): """Pretty-print the contents of :data:`DEFAULTS`""" maxlen = max([len(x) for x in DEFAULTS]) for key in DEFAULTS: value = DEFAULTS[key] if isinstance(value, (list, set)): value = ', '.join(value) print "%*s: %s" % (maxlen, key, value)
Code to handle the: option: -- delete command - line option.
def delete_dupes(groups, prefer_list=None, interactive=True, dry_run=False): """Code to handle the :option:`--delete` command-line option. :param groups: A list of groups of paths. :type groups: iterable :param prefer_list: A whitelist to be compiled by :func:`~fastdupes.multiglob_compile` and...
The main entry point compatible with setuptools.
def main(): """The main entry point, compatible with setuptools.""" # pylint: disable=bad-continuation from optparse import OptionParser, OptionGroup parser = OptionParser(usage="%prog [options] <folder path> ...", version="%s v%s" % (__appname__, __version__)) parser.add_option('-D', '-...
Use \\ r to overdraw the current line with the given text.
def write(self, text, newline=False): """Use ``\\r`` to overdraw the current line with the given text. This function transparently handles tracking how much overdrawing is necessary to erase the previous line when used consistently. :param text: The text to be outputted :param ...
select sentences in terms of maximum coverage problem
def summarize(text, char_limit, sentence_filter=None, debug=False): ''' select sentences in terms of maximum coverage problem Args: text: text to be summarized (unicode string) char_limit: summary length (the number of characters) Returns: list of extracted sentences Reference: ...
compute centrality score of sentences.
def lexrank(sentences, continuous=False, sim_threshold=0.1, alpha=0.9, use_divrank=False, divrank_alpha=0.25): ''' compute centrality score of sentences. Args: sentences: [u'こんにちは.', u'私の名前は飯沼です.', ... ] continuous: if True, apply continuous LexRank. (see reference) sim_thresh...
Args: text: text to be summarized ( unicode string ) sent_limit: summary length ( the number of sentences ) char_limit: summary length ( the number of characters ) imp_require: cumulative LexRank score [ 0. 0 - 1. 0 ]
def summarize(text, sent_limit=None, char_limit=None, imp_require=None, debug=False, **lexrank_params): ''' Args: text: text to be summarized (unicode string) sent_limit: summary length (the number of sentences) char_limit: summary length (the number of characters) imp_requ...
import summarizers on - demand
def get_summarizer(self, name): ''' import summarizers on-demand ''' if name in self.summarizers: pass elif name == 'lexrank': from . import lexrank self.summarizers[name] = lexrank.summarize elif name == 'mcp': from . impor...
Args: text: text to be summarized algo: summarizaion algorithm - lexrank ( default ) graph - based - clexrank Continuous LexRank - divrank DivRank ( Diverse Rank ) - mcp select sentences in terms of maximum coverage problem
def summarize(self, text=None, algo=u'lexrank', **summarizer_params): ''' Args: text: text to be summarized algo: summarizaion algorithm - 'lexrank' (default) graph-based - 'clexrank' Continuous LexRank - 'divrank' DivRank (Diverse Rank) ...
Args: text: unicode string that contains multiple Japanese sentences. delimiters: set () of sentence delimiter characters. parenthesis: to be checked its correspondence. Returns: generator that yields sentences.
def sent_splitter_ja(text, delimiters=set(u'。.?!\n\r'), parenthesis=u'()「」『』“”'): ''' Args: text: unicode string that contains multiple Japanese sentences. delimiters: set() of sentence delimiter characters. parenthesis: to be checked its correspondence. Returns: ...
Returns the DivRank ( Diverse Rank ) of the nodes in the graph. This code is based on networkx. pagerank.
def divrank(G, alpha=0.25, d=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): ''' Returns the DivRank (Diverse Rank) of the nodes in the graph. This code is based on networkx.pagerank. Args: (diff from pagerank) alpha: con...
Returns the DivRank ( Diverse Rank ) of the nodes in the graph. This code is based on networkx. pagerank_scipy
def divrank_scipy(G, alpha=0.25, d=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight='weight', dangling=None): ''' Returns the DivRank (Diverse Rank) of the nodes in the graph. This code is based on networkx.pagerank_scipy ''' import scipy....
Return an error code between 0 and 99.
def code_mapping(level, msg, default=99): """Return an error code between 0 and 99.""" try: return code_mappings_by_level[level][msg] except KeyError: pass # Following assumes any variable messages take the format # of 'Fixed text "variable text".' only: # e.g. 'Unknown directive...
Remove the quotes delimiting a docstring.
def dequote_docstring(text): """Remove the quotes delimiting a docstring.""" # TODO: Process escaped characters unless raw mode? text = text.strip() if len(text) > 6 and text[:3] == text[-3:] == '"""': # Standard case, """...""" return text[3:-3] if len(text) > 7 and text[:4] in ('u"...
Return True iff this function should be considered public.
def is_public(self): """Return True iff this function should be considered public.""" if self.all is not None: return self.name in self.all else: return not self.name.startswith("_")
Return True iff this method should be considered public.
def is_public(self): """Return True iff this method should be considered public.""" # Check if we are a setter/deleter method, and mark as private if so. for decorator in self.decorators: # Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo' if re.compile(r"^{}\.".for...
Return True iff this class should be considered public.
def is_public(self): """Return True iff this class should be considered public.""" return ( not self.name.startswith("_") and self.parent.is_class and self.parent.is_public )
Move.
def move(self): """Move.""" previous = self.current current = self._next_from_generator() self.current = None if current is None else Token(*current) self.line = self.current.start[0] if self.current else self.line self.got_logical_newline = previous.kind in self.LOGICAL_...
Parse the given file - like object and return its Module object.
def parse(self, filelike, filename): """Parse the given file-like object and return its Module object.""" self.log = log self.source = filelike.readlines() src = "".join(self.source) # This may raise a SyntaxError: compile(src, filename, "exec") self.stream = Toke...
Consume one token and verify it is of the expected kind.
def consume(self, kind): """Consume one token and verify it is of the expected kind.""" next_token = self.stream.move() assert next_token.kind == kind
Skip tokens in the stream until a certain token kind is reached.
def leapfrog(self, kind, value=None): """Skip tokens in the stream until a certain token kind is reached. If `value` is specified, tokens whose values are different will also be skipped. """ while self.current is not None: if self.current.kind == kind and ( ...
Parse a single docstring and return its value.
def parse_docstring(self): """Parse a single docstring and return its value.""" self.log.debug( "parsing docstring, token is %r (%s)", self.current.kind, self.current.value ) while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL): self.stream.move() ...