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 run_stacker(self, command='diff'): # pylint: disable=too-many-branches,too-many-locals """Run Stacker."""
response = {'skipped_configs': False} stacker_cmd = [command, "--region=%s" % self.context.env_region] if command == 'destroy': stacker_cmd.append('--force') elif command == 'build': if 'CI' in self.context.env_vars: stacker_cmd.append('--recreat...
<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_cf_distribution_class(): """Return the correct troposphere CF distribution class."""
if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): cf_dist = cloudfront.Distribution cf_dist.props['DistributionConfig'] = (DistributionConfig, True) return cf_dist return cloudfront.Distribution
<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_s3_origin_conf_class(): """Return the correct S3 Origin Config class for troposphere."""
if LooseVersion(troposphere.__version__) > LooseVersion('2.4.0'): return cloudfront.S3OriginConfig if LooseVersion(troposphere.__version__) == LooseVersion('2.4.0'): return S3OriginConfig return cloudfront.S3Origin
<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_available(self, show=None): """ Sets the agent availability to True. Args: show (aioxmpp.PresenceShow, optional): the show state of the presence (Defaul...
show = self.state.show if show is None else show self.set_presence(PresenceState(available=True, show=show))
<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_unavailable(self): """Sets the agent availability to False."""
show = PresenceShow.NONE self.set_presence(PresenceState(available=False, show=show))
<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_presence(self, state=None, status=None, priority=None): """ Change the presence broadcast by the client. If the client is currently connected, the new pr...
state = state if state is not None else self.state status = status if status is not None else self.status priority = priority if priority is not None else self.priority self.presenceserver.set_presence(state, status, priority)
<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_contacts(self): """ Returns list of contacts Returns: dict: the roster of contacts """
for jid, item in self.roster.items.items(): try: self._contacts[jid.bare()].update(item.export_as_json()) except KeyError: self._contacts[jid.bare()] = item.export_as_json() return self._contacts
<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_contact(self, jid): """ Returns a contact Args: jid (aioxmpp.JID): jid of the contact Returns: dict: the roster of contacts """
try: return self.get_contacts()[jid.bare()] except KeyError: raise ContactNotFound except AttributeError: raise AttributeError("jid must be an aioxmpp.JID object")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def subscribe(self, peer_jid): """ Asks for subscription Args: peer_jid (str): the JID you ask for subscriptiion """
self.roster.subscribe(aioxmpp.JID.fromstr(peer_jid).bare())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unsubscribe(self, peer_jid): """ Asks for unsubscription Args: peer_jid (str): the JID you ask for unsubscriptiion """
self.roster.unsubscribe(aioxmpp.JID.fromstr(peer_jid).bare())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def approve(self, peer_jid): """ Approve a subscription request from jid Args: peer_jid (str): the JID to approve """
self.roster.approve(aioxmpp.JID.fromstr(peer_jid).bare())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, event, category=None): """ Adds a new event to the trace store. The event may hava a category Args: event (spade.message.Message): the event to...
date = datetime.datetime.now() self.store.insert(0, (date, event, category)) if len(self.store) > self.size: del self.store[-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 filter(self, limit=None, to=None, category=None): """ Returns the events that match the filters Args: limit (int, optional): the max length of the events to...
if category and not to: msg_slice = itertools.islice((x for x in self.store if x[2] == category), limit) elif to and not category: to = JID.fromstr(to) msg_slice = itertools.islice((x for x in self.store if _agent_in_msg(to, x[1])), limit) elif to and categor...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self, auto_register=True): """ Tells the container to start this agent. It returns a coroutine or a future depending on whether it is called from a cor...
return self.container.start_agent(agent=self, auto_register=auto_register)
<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 _async_connect(self): # pragma: no cover """ connect and authenticate to the XMPP server. Async mode. """
try: self.conn_coro = self.client.connected() aenter = type(self.conn_coro).__aenter__(self.conn_coro) self.stream = await aenter logger.info(f"Agent {str(self.jid)} connected and authenticated.") except aiosasl.AuthenticationFailure: raise Au...
<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 _async_register(self): # pragma: no cover """ Register the agent in the XMPP server from a coroutine. """
metadata = aioxmpp.make_security_layer(None, no_verify=not self.verify_security) query = ibr.Query(self.jid.localpart, self.password) _, stream, features = await aioxmpp.node.connect_xmlstream(self.jid, metadata, loop=self.loop) await ibr.register(stream, query)
<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_avatar_url(jid): """ Static method to build a gravatar url with the agent's JID Args: jid (aioxmpp.JID): an XMPP identifier Returns: str: an URL for t...
digest = md5(str(jid).encode("utf-8")).hexdigest() return "http://www.gravatar.com/avatar/{md5}?d=monsterid".format(md5=digest)
<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_behaviour(self, behaviour, template=None): """ Adds and starts a behaviour to the agent. If template is not None it is used to match new messages and del...
behaviour.set_agent(self) if issubclass(type(behaviour), FSMBehaviour): for _, state in behaviour.get_states().items(): state.set_agent(self) behaviour.set_template(template) self.behaviours.append(behaviour) if self.is_alive(): behaviour....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_behaviour(self, behaviour): """ Removes a behaviour from the agent. The behaviour is first killed. Args: behaviour (spade.behaviour.CyclicBehaviour): ...
if not self.has_behaviour(behaviour): raise ValueError("This behaviour is not registered") index = self.behaviours.index(behaviour) self.behaviours[index].kill() self.behaviours.pop(index)
<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 _async_stop(self): """ Stops an agent and kills all its behaviours. """
if self.presence: self.presence.set_unavailable() for behav in self.behaviours: behav.kill() if self.web.is_started(): await self.web.runner.cleanup() """ Discconnect from XMPP server. """ if self.is_alive(): # Disconnect from XMP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _message_received(self, msg): """ Callback run when an XMPP Message is reveived. This callback delivers the message to every behaviour that is waiting for it...
msg = Message.from_node(msg) return self.dispatch(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dispatch(self, msg): """ Dispatch the message to every behaviour that is waiting for it using their templates match. Args: msg (spade.message.Messagge): the...
logger.debug(f"Got message: {msg}") futures = [] matched = False for behaviour in (x for x in self.behaviours if x.match(msg)): futures.append(self.submit(behaviour.enqueue(msg))) logger.debug(f"Message enqueued to behaviour: {behaviour}") self.traces...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_node(cls, node): """ Creates a new spade.message.Message from an aixoxmpp.stanza.Message Args: node (aioxmpp.stanza.Message): an aioxmpp Message Return...
if not isinstance(node, aioxmpp.stanza.Message): raise AttributeError("node must be a aioxmpp.stanza.Message instance") msg = cls() msg._to = node.to msg._sender = node.from_ if None in node.body: msg.body = node.body[None] else: for k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to(self, jid: str): """ Set jid of the receiver. Args: jid (str): the jid of the receiver. """
if jid is not None and not isinstance(jid, str): raise TypeError("'to' MUST be a string") self._to = aioxmpp.JID.fromstr(jid) if jid is not None else 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 sender(self, jid: str): """ Set jid of the sender Args: jid (str): jid of the sender """
if jid is not None and not isinstance(jid, str): raise TypeError("'sender' MUST be a string") self._sender = aioxmpp.JID.fromstr(jid) if jid is not None else 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 thread(self, value: str): """ Set thread id of the message Args: value (str): the thread id """
if value is not None and not isinstance(value, str): raise TypeError("'thread' MUST be a string") self._thread = value
<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_metadata(self, key: str, value: str): """ Add a new metadata to the message Args: key (str): name of the metadata value (str): value of the metadata ""...
if not isinstance(key, str) or not isinstance(value, str): raise TypeError("'key' and 'value' of metadata MUST be strings") self.metadata[key] = value
<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_metadata(self, key) -> str: """ Get the value of a metadata. Returns None if metadata does not exist. Args: key (str): name of the metadata Returns: str:...
return self.metadata[key] if key in self.metadata else 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 match(self, message) -> bool: """ Returns wether a message matches with this message or not. The message can be a Message object or a Template object. Args: m...
if self.to and message.to != self.to: return False if self.sender and message.sender != self.sender: return False if self.body and message.body != self.body: return False if self.thread and message.thread != self.thread: 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_reply(self): """ Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and r...
return Message( to=str(self.sender), sender=str(self.to), body=self.body, thread=self.thread, metadata=self.metadata )
<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(self): """ Returns an aioxmpp.stanza.Message built from the Message and prepared to be sent. Returns: aioxmpp.stanza.Message: the message prepared to...
msg = aioxmpp.stanza.Message( to=self.to, from_=self.sender, type_=aioxmpp.MessageType.CHAT, ) msg.body[None] = self.body # Send metadata using xep-0004: Data Forms (https://xmpp.org/extensions/xep-0004.html) if len(self.metadata): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unused_port(hostname): """Return a port that is unused on the current host."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((hostname, 0)) return s.getsockname()[1]
<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 start_server_in_loop(runner, hostname, port, agent): """ Listens to http requests and sends them to the webapp. Args: runner: AppRunner to process the ...
await runner.setup() agent.web.server = aioweb.TCPSite(runner, hostname, port) await agent.web.server.start() logger.info(f"Serving on http://{hostname}:{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 start(self, hostname=None, port=None, templates_path=None): """ Starts the web interface. Args: hostname (str, optional): host name to listen from. (Default...
self.hostname = hostname if hostname else "localhost" if port: self.port = port elif not self.port: self.port = unused_port(self.hostname) if templates_path: self.loaders.insert(0, jinja2.FileSystemLoader(templates_path)) self._set_loaders...
<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_get(self, path, controller, template, raw=False): """ Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutin...
if raw: fn = controller else: fn = self._prepare_controller(controller, template) self.app.router.add_get(path, fn)
<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_agent(self, agent): """ Links behaviour with its owner agent Args: agent (spade.agent.Agent): the agent who owns the behaviour """
self.agent = agent self.queue = asyncio.Queue(loop=self.agent.loop) self.presence = agent.presence self.web = agent.web
<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(self, message: Message) -> bool: """ Matches a message with the behaviour's template Args: message(spade.message.Message): the message to match with Re...
if self.template: return self.template.match(message) 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 set(self, name: str, value: Any) -> None: """ Stores a knowledge item in the agent knowledge base. Args: name (str): name of the item value (Any): value of ...
self.agent.set(name, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """starts behaviour in the event loop"""
self.agent.submit(self._start()) self.is_running = True
<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 _start(self): """ Start coroutine. runs on_start coroutine and then runs the _step coroutine where the body of the behaviour is called. """
self.agent._alive.wait() try: await self.on_start() except Exception as e: logger.error("Exception running on_start in behaviour {}: {}".format(self, e)) self.kill(exit_code=e) await self._step() self._is_done.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self, exit_code: Any = None): """ Stops the behaviour Args: exit_code (object, optional): the exit code of the behaviour (Default value = None) """
self._force_kill.set() if exit_code is not None: self._exit_code = exit_code logger.info("Killing behavior {0} with exit code: {1}".format(self, exit_code))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exit_code(self) -> Any: """ Returns the exit_code of the behaviour. It only works when the behaviour is done or killed, otherwise it raises an exception. Retu...
if self._done() or self.is_killed(): return self._exit_code else: raise BehaviourNotFinishedException
<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 send(self, msg: Message): """ Sends a message. Args: msg (spade.message.Message): the message to be sent. """
if not msg.sender: msg.sender = str(self.agent.jid) logger.debug(f"Adding agent's jid as sender to message: {msg}") await self.agent.container.send(msg, self) msg.sent = True self.agent.traces.append(msg, category=str(self))
<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 receive(self, timeout: float = None) -> Union[Message, None]: """ Receives a message for this behaviour. If timeout is not None it returns the message o...
if timeout: coro = self.queue.get() try: msg = await asyncio.wait_for(coro, timeout=timeout) except asyncio.TimeoutError: msg = None else: try: msg = self.queue.get_nowait() except asyncio.QueueE...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def period(self, value: float): """ Set the period. Args: value (float): seconds """
if value < 0: raise ValueError("Period must be greater or equal than zero.") self._period = timedelta(seconds=value)
<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_state(self, name: str, state: State, initial: bool = False): """ Adds a new state to the FSM. Args: name (str): the name of the state, which is used as ...
if not issubclass(state.__class__, State): raise AttributeError("state must be subclass of spade.behaviour.State") self._states[name] = state if initial: self.current_state = 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 add_transition(self, source: str, dest: str): """ Adds a transition from one state to another. Args: source (str): the name of the state from where the tran...
self._transitions[source].append(dest)
<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_valid_transition(self, source: str, dest: str) -> bool: """ Checks if a transitions is registered in the FSM Args: source (str): the source state name des...
if dest not in self._states or source not in self._states: raise NotValidState elif dest not in self._transitions[source]: raise NotValidTransition 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 to_graphviz(self) -> str: """ Converts the FSM behaviour structure to Graphviz syntax Returns: str: the graph in Graphviz syntax """
graph = "digraph finite_state_machine { rankdir=LR; node [fixedsize=true];" for origin, dest in self._transitions.items(): origin = origin.replace(" ", "_") for d in dest: d = d.replace(" ", "_") graph += "{0} -> {1};".format(origin, d) gr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def resample(x, sr_orig, sr_new, axis=-1, filter='kaiser_best', **kwargs): '''Resample a signal x from sr_orig to sr_new along a given axis. Parameters ---------- x : np.ndarray, dtype=np.float* The input signal(s) to resample. sr_orig : int > 0 The sampling rate of x sr_new :...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sinc_window(num_zeros=64, precision=9, window=None, rolloff=0.945): '''Construct a windowed sinc interpolation filter Parameters ---------- num_zeros : int > 0 The number of zero-crossings to retain in the sinc filter precision : int > 0 The number of filter coefficients to 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 get_filter(name_or_function, **kwargs): '''Retrieve a window given its name or function handle. Parameters ---------- name_or_function : str or callable If a function, returns `name_or_function(**kwargs)`. If a string, and it matches the name of one of the defined filter fu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_filter(filter_name): '''Retrieve a pre-computed filter. Parameters ---------- filter_name : str The key of the filter, e.g., 'kaiser_fast' Returns ------- half_window : np.ndarray The right wing of the interpolation filter precision : int > 0 The numbe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def default_values_of(func): """Return the defaults of the function `func`."""
signature = inspect.signature(func) return [k for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty or v.kind != inspect.Parameter.POSITIONAL_OR_KEYWORD]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def required_arguments(func): """Return all arguments of a function that do not have a default value."""
defaults = default_values_of(func) args = arguments_of(func) if defaults: args = args[:-len(defaults)] return args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, s...
merged_style = merge_styles([DEFAULT_STYLE, style]) validator = build_validator(validate) def get_prompt_tokens(): return [("class:qmark", qmark), ("class:question", ' {} '.format(message))] p = PromptSession(get_prompt_tokens, style=merged_style, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip_if(self, condition: bool, default: Any = None) -> 'Question': """Skip the question if flag is set and return the default instead."""
self.should_skip_question = condition self.default = default 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 _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the de...
default_container = ps.layout.container default_buffer_window = \ default_container.get_children()[0].content.get_children()[1].content assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections de...
<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_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs) -> Layout: """Create a layout combining quest...
ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout(HSplit([ ps.layout.container, ConditionalContainer( Window(ic), filter=~IsDone() ) ]))
<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(c: Union[Text, 'Choice', Dict[Text, Any]]) -> 'Choice': """Create a choice object from different representations."""
if isinstance(c, Choice): return c elif isinstance(c, str): return Choice(c, c) else: return Choice(c.get('name'), c.get('value'), c.get('disabled', None), c.get('checked'), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFI...
return text.text(message, default, validate, qmark, style, is_password=True, **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 form(**kwargs: Question): """Create a form with multiple questions. The parameter name of a question will be the key for the answer in the returned dict."""
return Form(*(FormField(k, q) for k, q in kwargs.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 prompt(questions: List[Dict[Text, Any]], answers: Optional[Dict[Text, Any]] = None, patch_stdout: bool = False, true_color: bool = False, kbi_msg: Text = DEFA...
if isinstance(questions, dict): questions = [questions] answers = answers or {} for question_config in questions: # import the question if 'type' not in question_config: raise PromptParameterException('type') if 'name' not in question_config: raise...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def confirm(message: Text, default: bool = True, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, **kwargs: Any) -> Question: """Prompt the u...
merged_style = merge_styles([DEFAULT_STYLE, style]) status = {'answer': None} def get_prompt_tokens(): tokens = [] tokens.append(("class:qmark", qmark)) tokens.append(("class:question", ' {} '.format(message))) if status['answer'] is not None: answer = ' {}'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rawselect(message: Text, choices: List[Union[Text, Choice, Dict[Text, Any]]], default: Optional[Text] = None, qmark: Text = DEFAULT_QUESTION_PREFIX, style: Op...
return select.select(message, choices, default, qmark, style, use_shortcuts=True, **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 _discover_models(self): """ Return a dict containing a list of cassandra.cqlengine.Model classes within installed App. """
apps = get_installed_apps() connection = self.connection.connection.alias keyspace = self.connection.connection.keyspace for app in apps: self._cql_models[app.__name__] = get_cql_models( app, connection=connection, keyspace=keyspace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def django_table_names(self, only_existing=False, **kwargs): """ Returns a list of all table names that have associated cqlengine models and are present in setti...
all_models = list(chain.from_iterable(self.cql_models.values())) tables = [model.column_family_name(include_keyspace=False) for model in all_models] return tables
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_names(self, cursor=None, **kwargs): """ Returns all table names in current keyspace """
# Avoid migration code being executed if cursor: return [] connection = self.connection.connection keyspace_name = connection.keyspace if not connection.cluster.schema_metadata_enabled and \ keyspace_name not in connection.cluster.metadata.keyspaces:...
<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_models_keyspace(self, keyspace): """Set keyspace for all connection models"""
for models in self.connection.introspection.cql_models.values(): for model in models: model.__keyspace__ = keyspace
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _import_management(): """ Import the 'management' module within each installed app, to register dispatcher events. """
from importlib import import_module for app_name in settings.INSTALLED_APPS: try: import_module('.management', app_name) except SystemError: # We get SystemError if INSTALLED_APPS contains the # name of a class rather than a modu...
<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_installed_apps(): """ Return list of all installed apps """
if django.VERSION >= (1, 7): from django.apps import apps return [a.models_module for a in apps.get_app_configs() if a.models_module is not None] else: from django.db import models return models.get_apps()
<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, *args, **options): """ Pretend django_cassandra_engine to be dummy database backend with no support for migrations. """
self._change_cassandra_engine_name('django.db.backends.dummy') try: super(Command, self).handle(*args, **options) finally: self._change_cassandra_engine_name('django_cassandra_engine')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sql_flush(self, style, tables, sequences, allow_cascade=False): """ Truncate all existing tables in current keyspace. :returns: an empty list """
for table in tables: qs = "TRUNCATE {}".format(table) self.connection.connection.execute(qs) return []
<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_field(self, field, **kwargs): """Add each field as a private field."""
getattr(self, self._private_fields_name).append(field) self._expire_cache(reverse=True) self._expire_cache(reverse=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 _give_columns_django_field_attributes(self): """ Add Django Field attributes to each cqlengine.Column instance. So that the Django Options class may interact...
methods_to_add = ( django_field_methods.value_from_object, django_field_methods.value_to_string, django_field_methods.get_attname, django_field_methods.get_cache_name, django_field_methods.pre_save, django_field_methods.get_prep_value, ...
<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_column(cls, name): """ Based on cqlengine.models.BaseModel._get_column. But to work with 'pk' """
if name == 'pk': return cls._meta.get_field(cls._meta.pk.name) return cls._columns[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 _get_next(request): """ The part that's the least straightforward about views in this module is how they determine their redirects after they have finished c...
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None))) if not next: next = request.path return 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 get_cache_key(user_or_username, size, prefix): """ Returns a cache key consisten of a username and image size. """
if isinstance(user_or_username, get_user_model()): user_or_username = get_username(user_or_username) key = six.u('%s_%s_%s') % (prefix, user_or_username, size) return six.u('%s_%s') % (slugify(key)[:100], hashlib.md5(force_bytes(key)).hexdigest())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cache_result(default_size=settings.AVATAR_DEFAULT_SIZE): """ Decorator to cache the result of functions that take a ``user`` and a ``size`` value. """
if not settings.AVATAR_CACHE_ENABLED: def decorator(func): return func return decorator def decorator(func): def cached_func(user, size=None, **kwargs): prefix = func.__name__ cached_funcs.add(prefix) key = get_cache_key(user, size or def...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def invalidate_cache(user, size=None): """ Function to be called when saving or changing an user's avatars. """
sizes = set(settings.AVATAR_AUTO_GENERATE_SIZES) if size is not None: sizes.add(size) for prefix in cached_funcs: for size in sizes: cache.delete(get_cache_key(user, size, prefix))
<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(self, institution_id, initial_products, _options=None, webhook=None, transactions__start_date=None, transactions__end_date=None, ): ''' Generate a public token for sandbox testing. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def from_response(response): ''' Create an error of the right class from an API response. :param response dict Response JSON ''' cls = PLAID_ERROR_TYPE_MAP.get(response['error_type'], PlaidError) return cls(response['error_message'], respon...
<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(self, access_tokens, days_requested, options=None): ''' Create an asset report. :param [str] access_tokens: A list of access tokens, one token for each Item to be included in the Asset ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def refresh(self, asset_report_token, days_requested, options=None): ''' Create a new, refreshed asset report based on an existing asset report. :param str asset_report_token: The existing Asset Report's asset ...
<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, asset_report_token, include_insights=False): ''' Retrieves an asset report. :param str asset_report_token: The asset report token for the asset report you created. :param bool include_insights: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post(self, path, data, is_json=True): '''Make a post request with client_id and secret key.''' post_data = { 'client_id': self.client_id, 'secret': self.secret, } post_data.update(data) return self._post(path, post_data, is_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post_public(self, path, data, is_json=True): '''Make a post request requiring no auth.''' return self._post(path, data, is_json)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def post_public_key(self, path, data, is_json=True): '''Make a post request using a public key.''' post_data = { 'public_key': self.public_key } post_data.update(data) return self._post(path, post_data, is_json)
<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_by_id(self, institution_id, _options=None): ''' Fetch a single institution by id. :param str institution_id: ''' options = _options or {} return self.client.post_public_key('/institutions/get_by_id', { 'institution_id': institution_id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def search(self, query, _options={}, products=None): ''' Search all institutions by name. :param str query: Query against the full list of institutions. :param [str] products: Filter FIs by available products. Optional. ''' ...
<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_avro(file_path_or_buffer, schema=None, **kwargs): """ Avro file reader. Args: file_path_or_buffer: Input file path or file-like object. schema: Avro sch...
if isinstance(file_path_or_buffer, six.string_types): with open(file_path_or_buffer, 'rb') as f: return __file_to_dataframe(f, schema, **kwargs) else: return __file_to_dataframe(file_path_or_buffer, schema, **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 to_avro(file_path_or_buffer, df, schema=None, codec='null', append=False): """ Avro file writer. Args: file_path_or_buffer: Output file path or file-like obj...
if schema is None: schema = __schema_infer(df) open_mode = 'wb' if not append else 'a+b' if isinstance(file_path_or_buffer, six.string_types): with open(file_path_or_buffer, open_mode) as f: fastavro.writer(f, schema=schema, records=df.to_dict('reco...
<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(self, x, w=1): """ Update the t-digest with value x and weight w. """
self.n += w if len(self) == 0: self._add_centroid(Centroid(x, w)) return S = self._find_closest_centroids(x) while len(S) != 0 and w > 0: j = choice(list(range(len(S)))) c_j = S[j] q = self._compute_centroid_quantile(c_j) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def batch_update(self, values, w=1): """ Update the t-digest with an iterable of values. This assumes all points have the same weight. """
for x in values: self.update(x, w) self.compress() return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def trimmed_mean(self, p1, p2): """ Computes the mean of the distribution between the two percentiles p1 and p2. This is a modified algorithm than the one presen...
if not (p1 < p2): raise ValueError("p1 must be between 0 and 100 and less than p2.") min_count = p1 / 100. * self.n max_count = p2 / 100. * self.n trimmed_sum = trimmed_count = curr_count = 0 for i, c in enumerate(self.C.values()): next_count = curr_cou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def centroids_to_list(self): """ Returns a Python list of the TDigest object's Centroid values. """
centroids = [] for key in self.C.keys(): tree_values = self.C.get_value(key) centroids.append({'m':tree_values.mean, 'c':tree_values.count}) return centroids
<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_from_dict(self, dict_values): """ Updates TDigest object with dictionary values. The digest delta and K values are optional if you would like to updat...
self.delta = dict_values.get('delta', self.delta) self.K = dict_values.get('K', self.K) self.update_centroids_from_list(dict_values['centroids']) 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 update_centroids_from_list(self, list_values): """ Add or update Centroids from a Python list. Any existing centroids in the digest object are appropriately ...
[self.update(value['m'], value['c']) for value in list_values] 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 is_undirected(matrix): """ Determine if the matrix reprensents a directed graph :param matrix: The matrix to tested :returns: boolean """
if isspmatrix(matrix): return sparse_allclose(matrix, matrix.transpose()) return np.allclose(matrix, matrix.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 convert_to_adjacency_matrix(matrix): """ Converts transition matrix into adjacency matrix :param matrix: The matrix to be converted :returns: adjacency matri...
for i in range(matrix.shape[0]): if isspmatrix(matrix): col = find(matrix[:,i])[2] else: col = matrix[:,i].T.tolist()[0] coeff = max( Fraction(c).limit_denominator().denominator for c in col ) matrix[:,i] *= coeff return matrix