text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pack(field: str, kwargs: Dict[str, Any], default: Optional[Any] = None, sep: str=',') -> str: """ Util for joining multiple fields with commas """
if default is not None: value = kwargs.get(field, default) else: value = kwargs[field] if isinstance(value, str): return value elif isinstance(value, collections.abc.Iterable): return sep.join(str(f) for f in value) else: return str(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def connect(self) -> None: """Open a connection to the defined server."""
def protocol_factory() -> Protocol: return Protocol(client=self) _, protocol = await self.loop.create_connection( protocol_factory, host=self.host, port=self.port, ssl=self.ssl ) # type: Tuple[Any, Any] if self.protocol: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def on(self, event: str, func: Optional[Callable] = None) -> Callable: """ Decorate a function to be invoked when the given event occurs. The function may be a co...
if func is None: return functools.partial(self.on, event) # type: ignore wrapped = func if not asyncio.iscoroutinefunction(wrapped): wrapped = asyncio.coroutine(wrapped) self._event_handlers[event.upper()].append(wrapped) # Always return original ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle(self, nick, target, message, **kwargs): """ client callback entrance """
for regex, (func, pattern) in self.routes.items(): match = regex.match(message) if match: self.client.loop.create_task( func(nick, target, message, match, **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def build_url(self, path, params=None): ''' Constructs the url for a cheddar API resource ''' url = u'%s/%s/productCode/%s' % ( self.endpoint, path, self.product_code, ) if params: for key, value in params.items(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make_request(self, path, params=None, data=None, method=None): ''' Makes a request to the cheddar api using the authentication and configuration settings available. ''' # Setup values url = self.build_url(path, params) client_log.debug('Requesting: %s' % url)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy(host='localhost', port=4304, flags=0, persistent=False, verbose=False, ): """factory function that returns a proxy object for an owserver at host, port...
# resolve host name/port try: gai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP) except socket.gaierror as err: raise ConnError(*err.args) # gai is a (non empty) list of tuples, search for the first working one assert g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone(proxy, persistent=True): """factory function for cloning a proxy object"""
if not isinstance(proxy, _Proxy): raise TypeError('argument is not a Proxy object') if persistent: pclass = _PersistentProxy else: pclass = _Proxy return pclass(proxy._family, proxy._sockaddr, proxy.flags & ~FLG_PERSISTENCE, proxy.verbose, proxy.errmess)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def req(self, msgtype, payload, flags, size=0, offset=0, timeout=0): """send message to server and return response"""
if timeout < 0: raise ValueError("timeout cannot be negative!") tohead = _ToServerHeader(payload=len(payload), type=msgtype, flags=flags, size=size, offset=offset) tstartcom = monotonic() # set timer when communication begins self._send_m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_msg(self, header, payload): """send message to server"""
if self.verbose: print('->', repr(header)) print('..', repr(payload)) assert header.payload == len(payload) try: sent = self.socket.send(header + payload) except IOError as err: raise ConnError(*err.args) # FIXME FIXME FIXME: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_msg(self): """read message from server"""
# # NOTE: # '_recv_socket(nbytes)' was implemented as # 'socket.recv(nbytes, socket.MSG_WAITALL)' # but socket.MSG_WAITALL proved not reliable # def _recv_socket(nbytes): """read nbytes bytes from self.socket""" # # code bel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ping(self): """sends a NOP packet and waits response; returns None"""
ret, data = self.sendmess(MSG_NOP, bytes()) if data or ret > 0: raise ProtocolError('invalid reply to ping message') if ret < 0: raise OwnetError(-ret, self.errmess[-ret])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def present(self, path, timeout=0): """returns True if there is an entity at path"""
ret, data = self.sendmess(MSG_PRESENCE, str2bytez(path), timeout=timeout) assert ret <= 0 and not data, (ret, data) if ret < 0: return False else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dir(self, path='/', slash=True, bus=False, timeout=0): """list entities at path"""
if slash: msg = MSG_DIRALLSLASH else: msg = MSG_DIRALL if bus: flags = self.flags | FLG_BUS_RET else: flags = self.flags & ~FLG_BUS_RET ret, data = self.sendmess(msg, str2bytez(path), flags, timeout=timeout) if ret < 0: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read(self, path, size=MAX_PAYLOAD, offset=0, timeout=0): """read data at path"""
if size > MAX_PAYLOAD: raise ValueError("size cannot exceed %d" % MAX_PAYLOAD) ret, data = self.sendmess(MSG_READ, str2bytez(path), size=size, offset=offset, timeout=timeout) if ret < 0: raise OwnetError(-ret, self.errmess[-ret], path)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, path, data, offset=0, timeout=0): """write data at path path is a string, data binary; it is responsability of the caller ensure proper encoding....
# fixme: check of path type delayed to str2bytez if not isinstance(data, (bytes, bytearray, )): raise TypeError("'data' argument must be binary") ret, rdata = self.sendmess(MSG_WRITE, str2bytez(path) + data, size=len(data), offset=offset, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def delete_all_customers(self): ''' This method does exactly what you think it does. Calling this method deletes all customer data in your cheddar product and the configured gateway. This action cannot be undone. DO NOT RUN THIS UNLESS YOU REALLY, REALLY, REALLY MEAN T...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def initial_bill_date(self): ''' An estimated initial bill date for an account created today, based on available plan info. ''' time_to_start = None if self.initial_bill_count_unit == 'months': time_to_start = relativedelta(months=self.initial_bill_co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def charge(self, code, each_amount, quantity=1, description=None): ''' Add an arbitrary charge or credit to a customer's account. A positive number will create a charge. A negative number will create a credit. each_amount is normalized to a Decimal with a precision of 2 as tha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set(self, quantity): ''' Set the item's quantity to the passed in amount. If nothing is passed in, a quantity of 1 is assumed. If a decimal value is passsed in, it is rounded to the 4th decimal place as that is the level of precision which the Cheddar API accepts. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _is_compatible_with(self, other): """ Return True if names are not incompatible. This checks that the gender of titles and compatibility of suffixes """
title = self._compare_title(other) suffix = self._compare_suffix(other) return title and suffix
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compare_title(self, other): """Return False if titles have different gender associations"""
# If title is omitted, assume a match if not self.title or not other.title: return True titles = set(self.title_list + other.title_list) return not (titles & MALE_TITLES and titles & FEMALE_TITLES)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compare_suffix(self, other): """Return false if suffixes are mutually exclusive"""
# If suffix is omitted, assume a match if not self.suffix or not other.suffix: return True # Check if more than one unique suffix suffix_set = set(self.suffix_list + other.suffix_list) unique_suffixes = suffix_set & UNIQUE_SUFFIXES for key in EQUIVALENT_SUF...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compare_components(self, other, settings, ratio=False): """Return comparison of first, middle, and last components"""
first = compare_name_component( self.first_list, other.first_list, settings['first'], ratio, ) if settings['check_nickname']: if first is False: first = compare_name_component( self.nickname_list, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _determine_weights(self, other, settings): """ Return weights of name components based on whether or not they were omitted """
# TODO: Reduce weight for matches by prefix or initials first_is_used = settings['first']['required'] or \ self.first and other.first first_weight = settings['first']['weight'] if first_is_used else 0 middle_is_used = settings['middle']['required'] or \ self.m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limit(self, limit_value, key_func=None, per_method=False, methods=None, error_message=None, exempt_when=None): """ decorator to be used for rate limiting ind...
return self.__limit_decorator(limit_value, key_func, per_method=per_method, methods=methods, error_message=error_message, exempt_when=exempt_when)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def shared_limit(self, limit_value, scope, key_func=None, error_message=None, exempt_when=None): """ decorator to be applied to multiple routes sharing the same ...
return self.__limit_decorator( limit_value, key_func, True, scope, error_message=error_message, exempt_when=exempt_when )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """ resets the storage if it supports being reset """
try: self._storage.reset() self.logger.info("Storage has been reset and all limits cleared") except NotImplementedError: self.logger.warning("This storage type does not support being reset")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_soup(page=''): """ Returns a bs4 object of the page requested """
content = requests.get('%s/%s' % (BASE_URL, page)).text return BeautifulSoup(content)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. :param string fullnam...
if options is not None: settings = deepcopy(SETTINGS[strictness]) deep_update_dict(settings, options) else: settings = SETTINGS[strictness] name1 = Name(fullname1) name2 = Name(fullname2) return name1.deep_compare(name2, settings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ratio(fullname1, fullname2, strictness='default', options=None): """ Takes two names and returns true if they describe the same person. Uses difflib's sequen...
if options is not None: settings = deepcopy(SETTINGS[strictness]) deep_update_dict(settings, options) else: settings = SETTINGS[strictness] name1 = Name(fullname1) name2 = Name(fullname2) return name1.ratio_deep_compare(name2, settings)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_zipped_rows(self, soup): """ Returns all 'tr' tag rows as a list of tuples. Each tuple is for a single story. """
# the table with all submissions table = soup.findChildren('table')[2] # get all rows but last 2 rows = table.findChildren(['tr'])[:-2] # remove the spacing rows # indices of spacing tr's spacing = range(2, len(rows), 3) rows = [row for (i, row) i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_leaders(self, limit=10): """ Return the leaders of Hacker News """
if limit is None: limit = 10 soup = get_soup('leaders') table = soup.find('table') leaders_table = table.find_all('table')[1] listleaders = leaders_table.find_all('tr')[2:] listleaders.pop(10) # Removing because empty in the Leaders page for ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.findChildren('table')[3] elif current_page > 1: table = soup.findChildren('table')[2] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 r...
if not item_id: raise Exception('Need an item_id for a story') # get details about a particular story soup = get_item_soup(item_id) # this post has not been scraped, so we explititly get all info story_id = item_id rank = -1 # to extract m...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) != len(list2): return False compare_func = _ratio_compare if use_ratio else _normal_compare return compare_func(list1, list2, setting...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_regex, name1) name2 = re.sub(nickname_regex, root_regex, name2) if equate_prefix(name1, name2): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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-8')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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): deep_update_dict(default_setting, new_setting) else: default[key] = new_setting
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_songs] base_path = os.path.dirname(os.path.commonprefix(song_paths)) return base_path
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 n...
result = 0 bits = self._bits while bits: result += bits % 2 bits >>= 1 return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 e else: return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exchange_declare(self, exchange, type, durable, auto_delete): """Declare an named exchange."""
return self.channel.exchange_declare(exchange=exchange, type=type, durable=durable, auto_delete=auto_delete)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, arguments=arguments)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`` o...
raw_message = self.channel.basic_get(queue, no_ack=no_ack) if not raw_message: return None return self.message_to_python(raw_message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_encoding, payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_default_serializer(self, name): """ Set the default serialization method used by this library. :param name: The name of the registered serialization met...
try: (self._default_content_type, self._default_content_encoding, self._default_encode) = self._encoders[name] except KeyError: raise SerializerNotInstalled( "No encoder installed for %s" % name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
if serializer == "raw": return raw_encode(data) if serializer and not self._encoders.get(serializer): raise SerializerNotInstalled( "No encoder installed for %s" % serializer) # If a raw string was sent, assume binary encoding # (it's lik...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cover(cls, bits, wildcard_probability): """Create a new bit condition that matches the provided bit string, with the indicated per-index wildcard probability...
if not isinstance(bits, BitString): bits = BitString(bits) mask = BitString([ random.random() > wildcard_probability for _ in range(len(bits)) ]) return cls(bits, mask)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 childre...
assert isinstance(other, BitCondition) assert len(self) == len(other) template = BitString.crossover_template(len(self), points) inv_template = ~template bits1 = (self._bits & template) | (other._bits & inv_template) mask1 = (self._mask & template) | (other._mask & in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
retry_over_time(self.connect, self.connection_errors, (), {}, errback, max_retries, interval_start, interval_step, interval_max) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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": self.virtual_host, "port": port...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def payload(self): """The decoded message."""
if not self._decoded_cache: self._decoded_cache = self.decode() return self._decoded_cache
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reject(self): """Reject this message. The message will be discarded by the server. :raises MessageStateError: If the message has already been acknowledged/re...
if self.acknowledged: raise self.MessageStateError( "Message already acknowledged with state: %s" % self._state) self.backend.reject(self.delivery_tag) self._state = "REJECTED"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Message...
if self.acknowledged: raise self.MessageStateError( "Message already acknowledged with state: %s" % self._state) self.backend.requeue(self.delivery_tag) self._state = "REQUEUED"
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) _uuid_generate_random(buffer) return str(UUID(bytes=buffer.raw)) return str(uuid4())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 waitin...
if not mqueue.qsize(): return None message_data, content_type, content_encoding = mqueue.get() return self.Message(backend=self, body=message_data, content_type=content_type, content_encoding=content_encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def queue_purge(self, queue, **kwargs): """Discard all messages in the queue."""
qsize = mqueue.qsize() mqueue.queue.clear() return qsize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_message(self, message_data, delivery_mode, content_type, content_encoding, **kwargs): """Prepare message for sending."""
return (message_data, content_type, content_encoding)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_future_expectation(self, match_set): """Return a numerical value representing the expected future payoff of the previously selected action, given only th...
assert isinstance(match_set, MatchSet) assert match_set.algorithm is self return self.discount_factor * ( self.idealization_factor * match_set.best_prediction + (1 - self.idealization_factor) * match_set.prediction )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 Mat...
assert isinstance(match_set, MatchSet) assert match_set.algorithm is self if self.minimum_actions is None: return len(match_set) < len(match_set.model.possible_actions) else: return len(match_set) < self.minimum_actions
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
assert isinstance(match_set, MatchSet) assert match_set.model.algorithm is self # Create a new condition that matches the situation. condition = bitstrings.BitCondition.cover( match_set.situation, self.wildcard_probability ) # Pick a random act...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
assert isinstance(match_set, MatchSet) assert match_set.algorithm is self assert match_set.selected_action is not None payoff = float(match_set.payoff) action_set = match_set[match_set.selected_action] action_set_size = sum(rule.numerosity for rule in action_set) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 range over (0, 1]. total_accuracy = 0 accuracies = {} for rule in action_set: if rule.error < sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: if not (rule.experience > self.subsumption_threshold and rule...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.numerosity for rule in action_set) total_numerosity = sum(rule.numerosity for rule in action...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 cl...
total_fitness = sum(rule.fitness for rule in action_set) selector = random.uniform(0, total_fitness) for rule in action_set: selector -= rule.fitness if selector <= 0: return rule # If for some reason a case slips through the above loop, perhaps ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _mutate(self, condition, situation): """Create a new condition from the given one by probabilistically applying point-wise mutations. Bits that were original...
# Go through each position in the condition, randomly flipping # whether the position is a value (0 or 1) or a wildcard (#). We do # this in a new list because the original condition's mask is # immutable. mutation_points = bitstrings.BitString.random( len(condition...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, properties=properties, exchange=exchange, rout...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.queue_declare(queue=self.queue, durable=self.durable, exclusive=self.e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.B...
no_ack = no_ack or self.no_ack auto_ack = auto_ack or self.auto_ack message = self.backend.get(self.queue, no_ack=no_ack) if message: if auto_ack and not message.acknowledged: message.ack() if enable_callbacks: self.receive(message...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discard_all(self, filterfunc=None): """Discard all waiting messages. :param filterfunc: A filter function to only discard the messages this filter returns. :...
if not filterfunc: return self.backend.queue_purge(self.queue) if self.no_ack or self.auto_ack: raise Exception("discard_all: Can't use filter with auto/no-ack.") discarded_count = 0 while True: message = self.fetch() if message is None:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, nowait=True) self.chan...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def wait(self, limit=None): """Go into consume mode. Mostly for testing purposes and simple programs, you probably want :meth:`iterconsume` or :meth:`iterqueue` ...
it = self.iterconsume(limit) while True: it.next()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close the channel to the queue."""
self.cancel() self.backend.close() self._closed = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_message(self, message_data, delivery_mode=None, priority=None, content_type=None, content_encoding=None, serializer=None): """With any data, serialize...
delivery_mode = delivery_mode or self.delivery_mode # No content_type? Then we're serializing the data internally. if not content_type: serializer = serializer or self.serializer (content_type, content_encoding, message_data) = serialization.encode(message...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Close any open channels."""
self.consumer.close() self.publisher.close() self._closed = True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) self.consumers.append(consumer) return consumer
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self): """Declare consumers."""
head = self.consumers[:-1] tail = self.consumers[-1] [self._declare_consumer(consumer, nowait=True) for consumer in head] self._declare_consumer(tail, nowait=False)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterconsume(self, limit=None): """Cycle between all consumers in consume mode. See :meth:`Consumer.iterconsume`. """
self.consume() return self.backend.consume(limit=limit)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_readme(base_path=None): """Call the conversion routine on README.md to generate README.rst. Why do all this? Because pypi requires reStructuredText, bu...
if base_path: path = os.path.join(base_path, 'README.md') else: path = 'README.md' convert_md_to_rst(path) print("Successfully converted README.md to README.rst")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the scenario, starting it over for a new run. Usage: if not scenario.more(): scenario.reset() Arguments: None Return: None """
self.remaining_cycles = self.initial_training_cycles self.needle_index = random.randrange(self.input_size)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_possible_actions(self): """Return a sequence containing the possible actions that can be executed within the environment. Usage: possible_actions = scena...
possible_actions = self.wrapped.get_possible_actions() if len(possible_actions) <= 20: # Try to ensure that the possible actions are unique. Also, put # them into a list so we can iterate over them safely before # returning them; this avoids accidentally exhausting ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def more(self): """Return a Boolean indicating whether additional actions may be executed, per the reward program. Usage: while scenario.more(): situation = sce...
more = self.wrapped.more() if not self.steps % 100: self.logger.info('Steps completed: %d', self.steps) self.logger.info('Average reward per step: %.5f', self.total_reward / (self.steps or 1)) if not more: self.logger.info('Run c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_classifications(self): """Return the classifications made by the algorithm for this scenario. Usage: model.run(scenario, learn=False) classifications = s...
if bitstrings.using_numpy(): return numpy.array(self.classifications) else: return self.classifications
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_model(self, scenario): """Create and return a new classifier set initialized for handling the given scenario. Usage: scenario = MUXProblem() model = algo...
assert isinstance(scenario, scenarios.Scenario) return ClassifierSet(self, scenario.get_possible_actions())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _compute_prediction(self): """Compute the combined prediction and prediction weight for this action set. The combined prediction is the weighted average of t...
total_weight = 0 total_prediction = 0 for rule in self._rules.values(): total_weight += rule.prediction_weight total_prediction += (rule.prediction * rule.prediction_weight) self._prediction = total_prediction / (total_weight or 1...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def best_prediction(self): """The highest value from among the predictions made by the action sets in this match set."""
if self._best_prediction is None and self._action_sets: self._best_prediction = max( action_set.prediction for action_set in self._action_sets.values() ) return self._best_prediction