sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _get_next_page(self, soup, current_page): """ Get the relative url of the next page (The "More" link at the bottom of the page) """ # Get the table with all the comments: if current_page == 1: table = soup.findChildren('table')[3] elif cu...
Get the relative url of the next page (The "More" link at the bottom of the page)
entailment
def _build_comments(self, soup): """ For the story, builds and returns a list of Comment objects. """ comments = [] current_page = 1 while True: # Get the table holding all comments: if current_page == 1: table = soup.f...
For the story, builds and returns a list of Comment objects.
entailment
def fromid(self, item_id): """ Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int. """ if not item_id: raise Exception('Need an i...
Initializes an instance of Story for given item_id. It is assumed that the story referenced by item_id is valid and does not raise any HTTP errors. item_id is an int.
entailment
def compare_name_component(list1, list2, settings, use_ratio=False): """ Compare a list of names from a name component based on settings """ if not list1[0] or not list2[0]: not_required = not settings['required'] return not_required * 100 if use_ratio else not_required if len(list1...
Compare a list of names from a name component based on settings
entailment
def equate_initial(name1, name2): """ Evaluates whether names match, or one name is the initial of the other """ if len(name1) == 0 or len(name2) == 0: return False if len(name1) == 1 or len(name2) == 1: return name1[0] == name2[0] return name1 == name2
Evaluates whether names match, or one name is the initial of the other
entailment
def equate_prefix(name1, name2): """ Evaluates whether names match, or one name prefixes another """ if len(name1) == 0 or len(name2) == 0: return False return name1.startswith(name2) or name2.startswith(name1)
Evaluates whether names match, or one name prefixes another
entailment
def equate_nickname(name1, name2): """ Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison """ # Convert '-ie' and '-y' to the root name nickname_regex = r'(.)\1(y|ie)$' root_regex = r'\1' name1 = re.sub(nickname_regex, root...
Evaluates whether names match based on common nickname patterns This is not currently used in any name comparison
entailment
def make_ascii(word): """ Converts unicode-specific characters to their equivalent ascii """ if sys.version_info < (3, 0, 0): word = unicode(word) else: word = str(word) normalized = unicodedata.normalize('NFKD', word) return normalized.encode('ascii', 'ignore').decode('utf...
Converts unicode-specific characters to their equivalent ascii
entailment
def seq_ratio(word1, word2): """ Returns sequence match ratio for two words """ raw_ratio = SequenceMatcher(None, word1, word2).ratio() return int(round(100 * raw_ratio))
Returns sequence match ratio for two words
entailment
def deep_update_dict(default, options): """ Updates the values in a nested dict, while unspecified values will remain unchanged """ for key in options.keys(): default_setting = default.get(key) new_setting = options.get(key) if isinstance(default_setting, dict): d...
Updates the values in a nested dict, while unspecified values will remain unchanged
entailment
def template_to_base_path(template, google_songs): """Get base output path for a list of songs for download.""" if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [template_to_filepath(template, song) for song in google_song...
Get base output path for a list of songs for download.
entailment
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
entailment
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
entailment
def count(self): """Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1. """ result = 0 bits = self._bits while bi...
Returns the number of bits set to True in the bit string. Usage: assert BitString('00110').count() == 2 Arguments: None Return: An int, the number of bits with value 1.
entailment
def drain_events(self, allowed_methods=None, timeout=None): """Wait for an event on any channel.""" return self.wait_multi(self.channels.values(), timeout=timeout)
Wait for an event on any channel.
entailment
def wait_multi(self, channels, allowed_methods=None, timeout=None): """Wait for an event on a channel.""" chanmap = dict((chan.channel_id, chan) for chan in channels) chanid, method_sig, args, content = self._wait_multiple( chanmap.keys(), allowed_methods, timeout=timeout) ...
Wait for an event on a channel.
entailment
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
Establish connection to the AMQP broker.
entailment
def queue_exists(self, queue): """Check if a queue has been declared. :rtype bool: """ try: self.channel.queue_declare(queue=queue, passive=True) except AMQPChannelException, e: if e.amqp_reply_code == 404: return False raise ...
Check if a queue has been declared. :rtype bool:
entailment
def queue_delete(self, queue, if_unused=False, if_empty=False): """Delete queue by name.""" return self.channel.queue_delete(queue, if_unused, if_empty)
Delete queue by name.
entailment
def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" if warn_if_exists and self.queue_exists(queue): warnings.warn(QueueAlreadyExistsWarning( QueueAlreadyExistsWarning.__doc__)) ...
Declare a named queue.
entailment
def exchange_declare(self, exchange, type, durable, auto_delete): """Declare an named exchange.""" return self.channel.exchange_declare(exchange=exchange, type=type, durable=durable, ...
Declare an named exchange.
entailment
def queue_bind(self, queue, exchange, routing_key, arguments=None): """Bind queue to an exchange using a routing key.""" return self.channel.queue_bind(queue=queue, exchange=exchange, routing_key=routing_key, ...
Bind queue to an exchange using a routing key.
entailment
def get(self, queue, no_ack=False): """Receive a message from a declared queue by name. :returns: A :class:`Message` object if a message was received, ``None`` otherwise. If ``None`` was returned, it probably means there was no messages waiting on the queue. """ ...
Receive a message from a declared queue by name. :returns: A :class:`Message` object if a message was received, ``None`` otherwise. If ``None`` was returned, it probably means there was no messages waiting on the queue.
entailment
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
Returns an iterator that waits for one message at a time.
entailment
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.connection: return self.channel.basic_cancel(consumer_tag)
Cancel a channel by consumer tag.
entailment
def close(self): """Close the channel if open.""" if self._channel and self._channel.is_open: self._channel.close() self._channel_ref = None
Close the channel if open.
entailment
def qos(self, prefetch_size, prefetch_count, apply_global=False): """Request specific Quality of Service.""" self.channel.basic_qos(prefetch_size, prefetch_count, apply_global)
Request specific Quality of Service.
entailment
def channel(self): """If no channel exists, a new one is requested.""" if not self._channel: self._channel_ref = weakref.ref(self.connection.get_channel()) return self._channel
If no channel exists, a new one is requested.
entailment
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.hostname: raise KeyError("Missing hostname for AMQP connection.") if conninfo.userid is None: raise KeyError("Missing user id for AMQP connect...
Establish connection to the AMQP broker.
entailment
def declare_consumer(self, queue, no_ack, callback, consumer_tag, nowait=False): """Declare a consumer.""" return self.channel.basic_consume(queue=queue, no_ack=no_ack, callback=callback, ...
Declare a consumer.
entailment
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration if not self.channel.is_open: raise StopIteration ...
Returns an iterator that waits for one message at a time.
entailment
def cancel(self, consumer_tag): """Cancel a channel by consumer tag.""" if not self.channel.conn: return self.channel.basic_cancel(consumer_tag)
Cancel a channel by consumer tag.
entailment
def prepare_message(self, message_data, delivery_mode, priority=None, content_type=None, content_encoding=None): """Encapsulate data into a AMQP message.""" return amqp.Message(message_data, properties={ "delivery_mode": delivery_mode, "priority": priority...
Encapsulate data into a AMQP message.
entailment
def raw_encode(data): """Special case serializer.""" content_type = 'application/data' payload = data if isinstance(payload, unicode): content_encoding = 'utf-8' payload = payload.encode(content_encoding) else: content_encoding = 'binary' return content_type, content_enco...
Special case serializer.
entailment
def register_json(): """Register a encoder/decoder for JSON serialization.""" from anyjson import serialize as json_serialize from anyjson import deserialize as json_deserialize registry.register('json', json_serialize, json_deserialize, content_type='application/json', ...
Register a encoder/decoder for JSON serialization.
entailment
def register_yaml(): """Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates""" try: import yaml registry.register('yaml', yaml.safe_dump, yaml.safe_load, ...
Register a encoder/decoder for YAML serialization. It is slower than JSON, but allows for more data types to be serialized. Useful if you need to send data such as dates
entailment
def register_pickle(): """The fastest serialization method, but restricts you to python clients.""" import cPickle registry.register('pickle', cPickle.dumps, cPickle.loads, content_type='application/x-python-serialize', content_encoding='binary')
The fastest serialization method, but restricts you to python clients.
entailment
def register_msgpack(): """See http://msgpack.sourceforge.net/""" try: import msgpack registry.register('msgpack', msgpack.packs, msgpack.unpacks, content_type='application/x-msgpack', content_encoding='binary') except ImportError: def not_available(*...
See http://msgpack.sourceforge.net/
entailment
def register(self, name, encoder, decoder, content_type, content_encoding='utf-8'): """Register a new encoder/decoder. :param name: A convenience name for the serialization method. :param encoder: A method that will be passed a python data structure and should retu...
Register a new encoder/decoder. :param name: A convenience name for the serialization method. :param encoder: A method that will be passed a python data structure and should return a string representing the serialized data. If ``None``, then only a decoder will be registered. E...
entailment
def _set_default_serializer(self, name): """ Set the default serialization method used by this library. :param name: The name of the registered serialization method. For example, ``json`` (default), ``pickle``, ``yaml``, or any custom methods registered using :meth:`regi...
Set the default serialization method used by this library. :param name: The name of the registered serialization method. For example, ``json`` (default), ``pickle``, ``yaml``, or any custom methods registered using :meth:`register`. :raises SerializerNotInstalled: If the serial...
entailment
def encode(self, data, serializer=None): """ Serialize a data structure into a string suitable for sending as an AMQP message body. :param data: The message data to send. Can be a list, dictionary or a string. :keyword serializer: An optional string representing ...
Serialize a data structure into a string suitable for sending as an AMQP message body. :param data: The message data to send. Can be a list, dictionary or a string. :keyword serializer: An optional string representing the serialization method you want the data marshalle...
entailment
def decode(self, data, content_type, content_encoding): """Deserialize a data stream as serialized using ``encode`` based on :param:`content_type`. :param data: The message data to deserialize. :param content_type: The content-type of the data. (e.g., ``application/json``)....
Deserialize a data stream as serialized using ``encode`` based on :param:`content_type`. :param data: The message data to deserialize. :param content_type: The content-type of the data. (e.g., ``application/json``). :param content_encoding: The content-encoding of the data...
entailment
def ack(self): """Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError...
Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
entailment
def consume(self, limit=None): """Returns an iterator that waits for one message at a time.""" for total_message_count in count(): if limit and total_message_count >= limit: raise StopIteration self.drain_events() yield True
Returns an iterator that waits for one message at a time.
entailment
def random(cls, length, bit_prob=.5): """Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=....
Create a bit string of the given length, with the probability of each bit being set equal to bit_prob, which defaults to .5. Usage: # Create a random BitString of length 10 with mostly zeros. bits = BitString.random(10, bit_prob=.1) Arguments: length: An int...
entailment
def crossover_template(cls, length, points=2): """Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitSt...
Create a crossover template with the given number of points. The crossover template can be used as a mask to crossover two bitstrings of the same length. Usage: assert len(parent1) == len(parent2) template = BitString.crossover_template(len(parent1)) inv_temp...
entailment
def cover(cls, bits, wildcard_probability): """Create a new bit condition that matches the provided bit string, with the indicated per-index wildcard probability. Usage: condition = BitCondition.cover(bitstring, .33) assert condition(bitstring) Arguments: ...
Create a new bit condition that matches the provided bit string, with the indicated per-index wildcard probability. Usage: condition = BitCondition.cover(bitstring, .33) assert condition(bitstring) Arguments: bits: A BitString which the resulting condition m...
entailment
def crossover_with(self, other, points=2): """Perform 2-point crossover on this bit condition and another of the same length, returning the two resulting children. Usage: offspring1, offspring2 = condition1.crossover_with(condition2) Arguments: other: A second B...
Perform 2-point crossover on this bit condition and another of the same length, returning the two resulting children. Usage: offspring1, offspring2 = condition1.crossover_with(condition2) Arguments: other: A second BitCondition of the same length as this one. ...
entailment
def get_backend_cls(self): """Get the currently used backend class.""" backend_cls = self.backend_cls if not backend_cls or isinstance(backend_cls, basestring): backend_cls = get_backend_cls(backend_cls) return backend_cls
Get the currently used backend class.
entailment
def ensure_connection(self, errback=None, max_retries=None, interval_start=2, interval_step=2, interval_max=30): """Ensure we have a connection to the server. If not retry establishing the connection with the settings specified. :keyword errback: Optional callback called ea...
Ensure we have a connection to the server. If not retry establishing the connection with the settings specified. :keyword errback: Optional callback called each time the connection can't be established. Arguments provided are the exception raised and the interval that will ...
entailment
def close(self): """Close the currently open connection.""" try: if self._connection: backend = self.create_backend() backend.close_connection(self._connection) except socket.error: pass self._closed = True
Close the currently open connection.
entailment
def info(self): """Get connection info.""" backend_cls = self.backend_cls or "amqplib" port = self.port or self.create_backend().default_port return {"hostname": self.hostname, "userid": self.userid, "password": self.password, "virtual_host...
Get connection info.
entailment
def decode(self): """Deserialize the message body, returning the original python structure sent by the publisher.""" return serialization.decode(self.body, self.content_type, self.content_encoding)
Deserialize the message body, returning the original python structure sent by the publisher.
entailment
def payload(self): """The decoded message.""" if not self._decoded_cache: self._decoded_cache = self.decode() return self._decoded_cache
The decoded message.
entailment
def ack(self): """Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError...
Acknowledge this message as being processed., This will remove the message from the queue. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
entailment
def reject(self): """Reject this message. The message will be discarded by the server. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowledged: raise self.MessageStateError( "Me...
Reject this message. The message will be discarded by the server. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
entailment
def requeue(self): """Reject this message and put it back on the queue. You must not use this method as a means of selecting messages to process. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected. """ if self.acknowle...
Reject this message and put it back on the queue. You must not use this method as a means of selecting messages to process. :raises MessageStateError: If the message has already been acknowledged/requeued/rejected.
entailment
def gen_unique_id(): """Generate a unique id, having - hopefully - a very small chance of collission. For now this is provided by :func:`uuid.uuid4`. """ # Workaround for http://bugs.python.org/issue4607 if ctypes and _uuid_generate_random: buffer = ctypes.create_string_buffer(16) ...
Generate a unique id, having - hopefully - a very small chance of collission. For now this is provided by :func:`uuid.uuid4`.
entailment
def retry_over_time(fun, catch, args=[], kwargs={}, errback=None, max_retries=None, interval_start=2, interval_step=2, interval_max=30): """Retry the function over and over until max retries is exceeded. For each retry we sleep a for a while before we try again, this interval is increased for every...
Retry the function over and over until max retries is exceeded. For each retry we sleep a for a while before we try again, this interval is increased for every retry until the max seconds is reached. :param fun: The function to try :param catch: Exceptions to catch, can be either tuple or a single ...
entailment
def get(self, *args, **kwargs): """Get the next waiting message from the queue. :returns: A :class:`Message` instance, or ``None`` if there is no messages waiting. """ if not mqueue.qsize(): return None message_data, content_type, content_encoding = mque...
Get the next waiting message from the queue. :returns: A :class:`Message` instance, or ``None`` if there is no messages waiting.
entailment
def queue_purge(self, queue, **kwargs): """Discard all messages in the queue.""" qsize = mqueue.qsize() mqueue.queue.clear() return qsize
Discard all messages in the queue.
entailment
def prepare_message(self, message_data, delivery_mode, content_type, content_encoding, **kwargs): """Prepare message for sending.""" return (message_data, content_type, content_encoding)
Prepare message for sending.
entailment
def get_future_expectation(self, match_set): """Return a numerical value representing the expected future payoff of the previously selected action, given only the current match set. The match_set argument is a MatchSet instance representing the current match set. Usage: ...
Return a numerical value representing the expected future payoff of the previously selected action, given only the current match set. The match_set argument is a MatchSet instance representing the current match set. Usage: match_set = model.match(situation) expec...
entailment
def covering_is_required(self, match_set): """Return a Boolean indicating whether covering is required for the current match set. The match_set argument is a MatchSet instance representing the current match set before covering is applied. Usage: match_set = model.match(situa...
Return a Boolean indicating whether covering is required for the current match set. The match_set argument is a MatchSet instance representing the current match set before covering is applied. Usage: match_set = model.match(situation) if model.algorithm.covering_is_requi...
entailment
def cover(self, match_set): """Return a new classifier rule that can be added to the match set, with a condition that matches the situation of the match set and an action selected to avoid duplication of the actions already contained therein. The match_set argument is a MatchSet instance...
Return a new classifier rule that can be added to the match set, with a condition that matches the situation of the match set and an action selected to avoid duplication of the actions already contained therein. The match_set argument is a MatchSet instance representing the match set to ...
entailment
def distribute_payoff(self, match_set): """Distribute the payoff received in response to the selected action of the given match set among the rules in the action set which deserve credit for recommending the action. The match_set argument is the MatchSet instance which suggested the sele...
Distribute the payoff received in response to the selected action of the given match set among the rules in the action set which deserve credit for recommending the action. The match_set argument is the MatchSet instance which suggested the selected action and earned the payoff. ...
entailment
def update(self, match_set): """Update the classifier set from which the match set was drawn, e.g. by applying a genetic algorithm. The match_set argument is the MatchSet instance whose classifier set should be updated. Usage: match_set = model.match(situation) m...
Update the classifier set from which the match set was drawn, e.g. by applying a genetic algorithm. The match_set argument is the MatchSet instance whose classifier set should be updated. Usage: match_set = model.match(situation) match_set.select_action() mat...
entailment
def prune(self, model): """Reduce the classifier set's population size, if necessary, by removing lower-quality *rules. Return a list containing any rules whose numerosities dropped to zero as a result of this call. (The list may be empty, if no rule's numerosity dropped to 0.) The ...
Reduce the classifier set's population size, if necessary, by removing lower-quality *rules. Return a list containing any rules whose numerosities dropped to zero as a result of this call. (The list may be empty, if no rule's numerosity dropped to 0.) The model argument is a ClassifierSe...
entailment
def _update_fitness(self, action_set): """Update the fitness values of the rules belonging to this action set.""" # Compute the accuracy of each rule. Accuracy is inversely # proportional to error. Below a certain error threshold, accuracy # becomes constant. Accuracy values rang...
Update the fitness values of the rules belonging to this action set.
entailment
def _action_set_subsumption(self, action_set): """Perform action set subsumption.""" # Select a condition with maximum bit count among those having # sufficient experience and sufficiently low error. selected_rule = None selected_bit_count = None for rule in action_set: ...
Perform action set subsumption.
entailment
def _get_average_time_stamp(action_set): """Return the average time stamp for the rules in this action set.""" # This is the average value of the iteration counter upon the most # recent update of each rule in this action set. total_time_stamps = sum(rule.time_stamp * rule.numero...
Return the average time stamp for the rules in this action set.
entailment
def _select_parent(action_set): """Select a rule from this action set, with probability proportionate to its fitness, to act as a parent for a new rule in the classifier set. Return the selected rule.""" total_fitness = sum(rule.fitness for rule in action_set) selector = random.u...
Select a rule from this action set, with probability proportionate to its fitness, to act as a parent for a new rule in the classifier set. Return the selected rule.
entailment
def _mutate(self, condition, situation): """Create a new condition from the given one by probabilistically applying point-wise mutations. Bits that were originally wildcarded in the parent condition acquire their values from the provided situation, to ensure the child condition continues...
Create a new condition from the given one by probabilistically applying point-wise mutations. Bits that were originally wildcarded in the parent condition acquire their values from the provided situation, to ensure the child condition continues to match it.
entailment
def establish_connection(self): """Establish connection to the AMQP broker.""" conninfo = self.connection if not conninfo.port: conninfo.port = self.default_port credentials = pika.PlainCredentials(conninfo.userid, conninfo.password...
Establish connection to the AMQP broker.
entailment
def queue_purge(self, queue, **kwargs): """Discard all messages in the queue. This will delete the messages and results in an empty queue.""" return self.channel.queue_purge(queue=queue).message_count
Discard all messages in the queue. This will delete the messages and results in an empty queue.
entailment
def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None): """Declare a named queue.""" return self.channel.queue_declare(queue=queue, durable=durable, exclusive=e...
Declare a named queue.
entailment
def declare_consumer(self, queue, no_ack, callback, consumer_tag, nowait=False): """Declare a consumer.""" @functools.wraps(callback) def _callback_decode(channel, method, header, body): return callback((channel, method, header, body)) return self.channel.basic_...
Declare a consumer.
entailment
def close(self): """Close the channel if open.""" if self._channel and not self._channel.handler.channel_close: self._channel.close() self._channel_ref = None
Close the channel if open.
entailment
def prepare_message(self, message_data, delivery_mode, priority=None, content_type=None, content_encoding=None): """Encapsulate data into a AMQP message.""" properties = pika.BasicProperties(priority=priority, content_type=content_type, ...
Encapsulate data into a AMQP message.
entailment
def publish(self, message, exchange, routing_key, mandatory=None, immediate=None, headers=None): """Publish a message to a named exchange.""" body, properties = message if headers: properties.headers = headers ret = self.channel.basic_publish(body=body, ...
Publish a message to a named exchange.
entailment
def _generate_consumer_tag(self): """Generate a unique consumer tag. :rtype string: """ return "%s.%s%s" % ( self.__class__.__module__, self.__class__.__name__, self._next_consumer_tag())
Generate a unique consumer tag. :rtype string:
entailment
def declare(self): """Declares the queue, the exchange and binds the queue to the exchange.""" arguments = None routing_key = self.routing_key if self.exchange_type == "headers": arguments, routing_key = routing_key, "" if self.queue: self.backend...
Declares the queue, the exchange and binds the queue to the exchange.
entailment
def _receive_callback(self, raw_message): """Internal method used when a message is received in consume mode.""" message = self.backend.message_to_python(raw_message) if self.auto_ack and not message.acknowledged: message.ack() self.receive(message.payload, message)
Internal method used when a message is received in consume mode.
entailment
def fetch(self, no_ack=None, auto_ack=None, enable_callbacks=False): """Receive the next message waiting on the queue. :returns: A :class:`carrot.backends.base.BaseMessage` instance, or ``None`` if there's no messages to be received. :keyword enable_callbacks: Enable callbacks. The...
Receive the next message waiting on the queue. :returns: A :class:`carrot.backends.base.BaseMessage` instance, or ``None`` if there's no messages to be received. :keyword enable_callbacks: Enable callbacks. The message will be processed with all registered callbacks. Default is...
entailment
def receive(self, message_data, message): """This method is called when a new message is received by running :meth:`wait`, :meth:`process_next` or :meth:`iterqueue`. When a message is received, it passes the message on to the callbacks listed in the :attr:`callbacks` attribute. ...
This method is called when a new message is received by running :meth:`wait`, :meth:`process_next` or :meth:`iterqueue`. When a message is received, it passes the message on to the callbacks listed in the :attr:`callbacks` attribute. You can register callbacks using :meth:`register_call...
entailment
def discard_all(self, filterfunc=None): """Discard all waiting messages. :param filterfunc: A filter function to only discard the messages this filter returns. :returns: the number of messages discarded. *WARNING*: All incoming messages will be ignored and not processed. ...
Discard all waiting messages. :param filterfunc: A filter function to only discard the messages this filter returns. :returns: the number of messages discarded. *WARNING*: All incoming messages will be ignored and not processed. Example using filter: >>> def ...
entailment
def consume(self, no_ack=None): """Declare consumer.""" no_ack = no_ack or self.no_ack self.backend.declare_consumer(queue=self.queue, no_ack=no_ack, callback=self._receive_callback, consumer_tag=self.consumer_tag, ...
Declare consumer.
entailment
def wait(self, limit=None): """Go into consume mode. Mostly for testing purposes and simple programs, you probably want :meth:`iterconsume` or :meth:`iterqueue` instead. This runs an infinite loop, processing all incoming messages using :meth:`receive` to apply the message to a...
Go into consume mode. Mostly for testing purposes and simple programs, you probably want :meth:`iterconsume` or :meth:`iterqueue` instead. This runs an infinite loop, processing all incoming messages using :meth:`receive` to apply the message to all registered callbacks.
entailment
def iterqueue(self, limit=None, infinite=False): """Infinite iterator yielding pending messages, by using synchronous direct access to the queue (``basic_get``). :meth:`iterqueue` is used where synchronous functionality is more important than performance. If you can, use :meth:`itercons...
Infinite iterator yielding pending messages, by using synchronous direct access to the queue (``basic_get``). :meth:`iterqueue` is used where synchronous functionality is more important than performance. If you can, use :meth:`iterconsume` instead. :keyword limit: If set, the i...
entailment
def cancel(self): """Cancel a running :meth:`iterconsume` session.""" if self.channel_open: try: self.backend.cancel(self.consumer_tag) except KeyError: pass
Cancel a running :meth:`iterconsume` session.
entailment
def close(self): """Close the channel to the queue.""" self.cancel() self.backend.close() self._closed = True
Close the channel to the queue.
entailment
def qos(self, prefetch_size=0, prefetch_count=0, apply_global=False): """Request specific Quality of Service. This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and seman...
Request specific Quality of Service. This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. ...
entailment
def declare(self): """Declare the exchange. Creates the exchange on the broker. """ self.backend.exchange_declare(exchange=self.exchange, type=self.exchange_type, durable=self.durable, ...
Declare the exchange. Creates the exchange on the broker.
entailment
def create_message(self, message_data, delivery_mode=None, priority=None, content_type=None, content_encoding=None, serializer=None): """With any data, serialize it and encapsulate it in a AMQP message with the proper headers set.""" delivery_mode =...
With any data, serialize it and encapsulate it in a AMQP message with the proper headers set.
entailment
def send(self, message_data, routing_key=None, delivery_mode=None, mandatory=False, immediate=False, priority=0, content_type=None, content_encoding=None, serializer=None, exchange=None): """Send a message. :param message_data: The message data to send. Can be a list, ...
Send a message. :param message_data: The message data to send. Can be a list, dictionary or a string. :keyword routing_key: A custom routing key for the message. If not set, the default routing key set in the :attr:`routing_key` attribute is used. :keyword ...
entailment
def send(self, message_data, delivery_mode=None): """See :meth:`Publisher.send`""" self.publisher.send(message_data, delivery_mode=delivery_mode)
See :meth:`Publisher.send`
entailment
def close(self): """Close any open channels.""" self.consumer.close() self.publisher.close() self._closed = True
Close any open channels.
entailment
def _receive_callback(self, raw_message): """Internal method used when a message is received in consume mode.""" message = self.backend.message_to_python(raw_message) if self.auto_ack and not message.acknowledged: message.ack() try: decoded = message.decode() ...
Internal method used when a message is received in consume mode.
entailment
def add_consumer_from_dict(self, queue, **options): """Add another consumer from dictionary configuration.""" options.setdefault("routing_key", options.pop("binding_key", None)) consumer = Consumer(self.connection, queue=queue, backend=self.backend, **options) ...
Add another consumer from dictionary configuration.
entailment
def add_consumer(self, consumer): """Add another consumer from a :class:`Consumer` instance.""" consumer.backend = self.backend self.consumers.append(consumer)
Add another consumer from a :class:`Consumer` instance.
entailment