Instruction:
Can you generate the documentation for the following Python 3 function
def create_participant(worker_id, hit_id, assignment_id, mode):
    # Lock the table, triggering multiple simultaneous accesses to fail
    try:
        session.connection().execute("LOCK TABLE participant IN EXCLUSIVE MODE NOWAIT")
    except exc.OperationalError as e:
        e.orig = TransactionRollbackError()
        raise e

    missing = [p for p in (worker_id, hit_id, assignment_id) if p == "undefined"]
    if missing:
        msg = "/participant POST: required values were 'undefined'"
        return error_response(error_type=msg, status=403)

    fingerprint_hash = request.args.get("fingerprint_hash")
    try:
        fingerprint_found = models.Participant.query.filter_by(
            fingerprint_hash=fingerprint_hash
        ).one_or_none()
    except MultipleResultsFound:
        fingerprint_found = True

    if fingerprint_hash and fingerprint_found:
        db.logger.warning("Same browser fingerprint detected.")

        if mode == "live":
            return error_response(
                error_type="/participant POST: Same participant dectected.", status=403
            )

    already_participated = models.Participant.query.filter_by(
        worker_id=worker_id
    ).one_or_none()

    if already_participated:
        db.logger.warning("Worker has already participated.")
        return error_response(
            error_type="/participant POST: worker has already participated.", status=403
        )

    duplicate = models.Participant.query.filter_by(
        assignment_id=assignment_id, status="working"
    ).one_or_none()

    if duplicate:
        msg = """
            AWS has reused assignment_id while existing participant is
            working. Replacing older participant {}.
        """
        app.logger.warning(msg.format(duplicate.id))
        q.enqueue(worker_function, "AssignmentReassigned", None, duplicate.id)

    # Count working or beyond participants.
    nonfailed_count = (
        models.Participant.query.filter(
            (models.Participant.status == "working")
            | (models.Participant.status == "overrecruited")
            | (models.Participant.status == "submitted")
            | (models.Participant.status == "approved")
        ).count()
        + 1
    )

    recruiter_name = request.args.get("recruiter", "undefined")
    if not recruiter_name or recruiter_name == "undefined":
        recruiter = recruiters.from_config(_config())
        if recruiter:
            recruiter_name = recruiter.nickname

    # Create the new participant.
    participant = models.Participant(
        recruiter_id=recruiter_name,
        worker_id=worker_id,
        assignment_id=assignment_id,
        hit_id=hit_id,
        mode=mode,
        fingerprint_hash=fingerprint_hash,
    )

    exp = Experiment(session)

    overrecruited = exp.is_overrecruited(nonfailed_count)
    if overrecruited:
        participant.status = "overrecruited"

    session.add(participant)
    session.flush()  # Make sure we know the id for the new row
    result = {"participant": participant.__json__()}

    # Queue notification to others in waiting room
    if exp.quorum:
        quorum = {"q": exp.quorum, "n": nonfailed_count, "overrecruited": overrecruited}
        db.queue_message(WAITING_ROOM_CHANNEL, dumps(quorum))
        result["quorum"] = quorum

    # return the data
    return success_response(**result)

Response:
Create a participant.

    This route is hit early on. Any nodes the participant creates will be
    defined in reference to the participant object. You must specify the
    worker_id, hit_id, assignment_id, and mode in the url.


Instruction:
Create a Python 3 function to
get the participant with the given id.

Response:
def get_participant(participant_id):
    """Get the participant with the given id."""
    try:
        ppt = models.Participant.query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(
            error_type="/participant GET: no participant found", status=403
        )

    # return the data
    return success_response(participant=ppt.__json__())


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_network(network_id):
    try:
        net = models.Network.query.filter_by(id=network_id).one()
    except NoResultFound:
        return error_response(error_type="/network GET: no network found", status=403)

    # return the data
    return success_response(network=net.__json__())

Response: Get the network with the given id.


Instruction:
Write a Python 3 script for
creating a new question in the node tree.

Response:
def create_question(participant_id):
    """Send a POST request to the question table.

    Questions store information at the participant level, not the node
    level.
    You should pass the question (string) number (int) and response
    (string) as arguments.
    """
    # Get the participant.
    try:
        ppt = models.Participant.query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(
            error_type="/question POST no participant found", status=403
        )

    question = request_parameter(parameter="question")
    response = request_parameter(parameter="response")
    number = request_parameter(parameter="number", parameter_type="int")
    for x in [question, response, number]:
        if isinstance(x, Response):
            return x

    # Consult the recruiter regarding whether to accept a questionnaire
    # from the participant:
    rejection = ppt.recruiter.rejects_questionnaire_from(ppt)
    if rejection:
        return error_response(
            error_type="/question POST, status = {}, reason: {}".format(
                ppt.status, rejection
            ),
            participant=ppt,
        )

    try:
        # execute the request
        models.Question(
            participant=ppt, question=question, response=response, number=number
        )
        session.commit()
    except Exception:
        return error_response(error_type="/question POST server error", status=403)

    # return the data
    return success_response()


Instruction:
Implement a function in Python 3 to
get the node s neighbors

Response:
def node_neighbors(node_id):
    """Send a GET request to the node table.

    This calls the neighbours method of the node
    making the request and returns a list of descriptions of
    the nodes (even if there is only one).
    Required arguments: participant_id, node_id
    Optional arguments: type, connection

    After getting the neighbours it also calls
    exp.node_get_request()
    """
    exp = Experiment(session)

    # get the parameters
    node_type = request_parameter(
        parameter="node_type", parameter_type="known_class", default=models.Node
    )
    connection = request_parameter(parameter="connection", default="to")
    failed = request_parameter(parameter="failed", parameter_type="bool", optional=True)
    for x in [node_type, connection]:
        if type(x) == Response:
            return x

    # make sure the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(
            error_type="/node/neighbors, node does not exist",
            error_text="/node/{0}/neighbors, node {0} does not exist".format(node_id),
        )

    # get its neighbors
    if failed is not None:
        # This will always raise because "failed" is not a supported parameter.
        # We just want to pass the exception message back in the response:
        try:
            node.neighbors(type=node_type, direction=connection, failed=failed)
        except Exception as e:
            return error_response(error_type="node.neighbors", error_text=str(e))

    else:
        nodes = node.neighbors(type=node_type, direction=connection)
        try:
            # ping the experiment
            exp.node_get_request(node=node, nodes=nodes)
            session.commit()
        except Exception:
            return error_response(error_type="exp.node_get_request")

    return success_response(nodes=[n.__json__() for n in nodes])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_node(participant_id):
    exp = Experiment(session)

    # Get the participant.
    try:
        participant = models.Participant.query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(error_type="/node POST no participant found", status=403)

    # Make sure the participant status is working
    if participant.status != "working":
        error_type = "/node POST, status = {}".format(participant.status)
        return error_response(error_type=error_type, participant=participant)

    # execute the request
    network = exp.get_network_for_participant(participant=participant)
    if network is None:
        return Response(dumps({"status": "error"}), status=403)

    node = exp.create_node(participant=participant, network=network)
    assign_properties(node)
    exp.add_node_to_network(node=node, network=network)

    # ping the experiment
    exp.node_post_request(participant=participant, node=node)

    # return the data
    return success_response(node=node.__json__())

Response: Create a new node for the given participant.


Instruction:
Create a Python 3 function for
getting the vectors of a node.

Response:
def node_vectors(node_id):
    """Get the vectors of a node.

    You must specify the node id in the url.
    You can pass direction (incoming/outgoing/all) and failed
    (True/False/all).
    """
    exp = Experiment(session)
    # get the parameters
    direction = request_parameter(parameter="direction", default="all")
    failed = request_parameter(parameter="failed", parameter_type="bool", default=False)
    for x in [direction, failed]:
        if type(x) == Response:
            return x

    # execute the request
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(error_type="/node/vectors, node does not exist")

    try:
        vectors = node.vectors(direction=direction, failed=failed)
        exp.vector_get_request(node=node, vectors=vectors)
        session.commit()
    except Exception:
        return error_response(
            error_type="/node/vectors GET server error",
            status=403,
            participant=node.participant,
        )

    # return the data
    return success_response(vectors=[v.__json__() for v in vectors])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def node_received_infos(node_id):
    exp = Experiment(session)

    # get the parameters
    info_type = request_parameter(
        parameter="info_type", parameter_type="known_class", default=models.Info
    )
    if type(info_type) == Response:
        return info_type

    # check the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(
            error_type="/node/infos, node {} does not exist".format(node_id)
        )

    # execute the request:
    infos = node.received_infos(type=info_type)

    try:
        # ping the experiment
        exp.info_get_request(node=node, infos=infos)

        session.commit()
    except Exception:
        return error_response(
            error_type="info_get_request error",
            status=403,
            participant=node.participant,
        )

    return success_response(infos=[i.__json__() for i in infos])

Response: Get all the infos a node has been sent and has received.


Instruction:
How would you code a function in Python 3 to
create an info. The node id must be specified in the url. You must pass contents as an argument. info_type is an additional optional argument. If info_type is a custom subclass of Info it must be added to the known_classes of the experiment class.

Response:
def info_post(node_id):
    """Create an info.

    The node id must be specified in the url.

    You must pass contents as an argument.
    info_type is an additional optional argument.
    If info_type is a custom subclass of Info it must be
    added to the known_classes of the experiment class.
    """
    # get the parameters and validate them
    contents = request_parameter(parameter="contents")
    info_type = request_parameter(
        parameter="info_type", parameter_type="known_class", default=models.Info
    )
    for x in [contents, info_type]:
        if type(x) == Response:
            return x
    # check the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(error_type="/info POST, node does not exist")

    exp = Experiment(session)
    try:
        # execute the request
        info = info_type(origin=node, contents=contents)
        assign_properties(info)

        # ping the experiment
        exp.info_post_request(node=node, info=info)

        session.commit()
    except Exception:
        return error_response(
            error_type="/info POST server error",
            status=403,
            participant=node.participant,
        )

    # return the data
    return success_response(info=info.__json__())


Instruction:
Can you create a Python 3 function that
gets all the transmissions of a node.

Response:
def node_transmissions(node_id):
    """Get all the transmissions of a node.

    The node id must be specified in the url.
    You can also pass direction (to/from/all) or status (all/pending/received)
    as arguments.
    """
    exp = Experiment(session)

    # get the parameters
    direction = request_parameter(parameter="direction", default="incoming")
    status = request_parameter(parameter="status", default="all")
    for x in [direction, status]:
        if type(x) == Response:
            return x

    # check the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(error_type="/node/transmissions, node does not exist")

    # execute the request
    transmissions = node.transmissions(direction=direction, status=status)

    try:
        if direction in ["incoming", "all"] and status in ["pending", "all"]:
            node.receive()
            session.commit()
        # ping the experiment
        exp.transmission_get_request(node=node, transmissions=transmissions)
        session.commit()
    except Exception:
        return error_response(
            error_type="/node/transmissions GET server error",
            status=403,
            participant=node.participant,
        )

    # return the data
    return success_response(transmissions=[t.__json__() for t in transmissions])


Instruction:
Here you have a function in Python 3, explain what it does
def node_transmit(node_id):
    exp = Experiment(session)
    what = request_parameter(parameter="what", optional=True)
    to_whom = request_parameter(parameter="to_whom", optional=True)

    # check the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(error_type="/node/transmit, node does not exist")
    # create what
    if what is not None:
        try:
            what = int(what)
            what = models.Info.query.get(what)
            if what is None:
                return error_response(
                    error_type="/node/transmit POST, info does not exist",
                    participant=node.participant,
                )
        except Exception:
            try:
                what = exp.known_classes[what]
            except KeyError:
                msg = "/node/transmit POST, {} not in experiment.known_classes"
                return error_response(
                    error_type=msg.format(what), participant=node.participant
                )

    # create to_whom
    if to_whom is not None:
        try:
            to_whom = int(to_whom)
            to_whom = models.Node.query.get(to_whom)
            if to_whom is None:
                return error_response(
                    error_type="/node/transmit POST, recipient Node does not exist",
                    participant=node.participant,
                )
        except Exception:
            try:
                to_whom = exp.known_classes[to_whom]
            except KeyError:
                msg = "/node/transmit POST, {} not in experiment.known_classes"
                return error_response(
                    error_type=msg.format(to_whom), participant=node.participant
                )

    # execute the request
    try:
        transmissions = node.transmit(what=what, to_whom=to_whom)
        for t in transmissions:
            assign_properties(t)
        session.commit()
        # ping the experiment
        exp.transmission_post_request(node=node, transmissions=transmissions)
        session.commit()
    except Exception:
        return error_response(
            error_type="/node/transmit POST, server error", participant=node.participant
        )

    # return the data
    return success_response(transmissions=[t.__json__() for t in transmissions])

Response: Transmit a node to another node.


Instruction:
Create a Python 3 function for
getting all the transformations of a node.

Response:
def transformation_get(node_id):
    """Get all the transformations of a node.

    The node id must be specified in the url.

    You can also pass transformation_type.
    """
    exp = Experiment(session)

    # get the parameters
    transformation_type = request_parameter(
        parameter="transformation_type",
        parameter_type="known_class",
        default=models.Transformation,
    )
    if type(transformation_type) == Response:
        return transformation_type

    # check the node exists
    node = models.Node.query.get(node_id)
    if node is None:
        return error_response(
            error_type="/node/transformations, "
            "node {} does not exist".format(node_id)
        )

    # execute the request
    transformations = node.transformations(type=transformation_type)
    try:
        # ping the experiment
        exp.transformation_get_request(node=node, transformations=transformations)
        session.commit()
    except Exception:
        return error_response(
            error_type="/node/transformations GET failed", participant=node.participant
        )

    # return the data
    return success_response(transformations=[t.__json__() for t in transformations])


Instruction:
How would you code a function in Python 3 to
check that the assignment_id of the participant is unique.

Response:
def check_for_duplicate_assignments(participant):
    """Check that the assignment_id of the participant is unique.

    If it isnt the older participants will be failed.
    """
    participants = models.Participant.query.filter_by(
        assignment_id=participant.assignment_id
    ).all()
    duplicates = [
        p for p in participants if (p.id != participant.id and p.status == "working")
    ]
    for d in duplicates:
        q.enqueue(worker_function, "AssignmentAbandoned", None, d.id)


Instruction:
Given the following Python 3 function, write the documentation
def worker_failed():
    participant_id = request.args.get("participant_id")
    if not participant_id:
        return error_response(
            error_type="bad request", error_text="participantId parameter is required"
        )

    try:
        _worker_failed(participant_id)
    except KeyError:
        return error_response(
            error_type="ParticipantId not found: {}".format(participant_id)
        )

    return success_response(
        field="status", data="success", request_type="worker failed"
    )

Response: Fail worker. Used by bots only for now.


Instruction:
Here you have a function in Python 3, explain what it does
def worker_function(
    event_type, assignment_id, participant_id, node_id=None, details=None
):
    """Process the notification."""
    _config()
    try:
        db.logger.debug(
            "rq: worker_function working on job id: %s", get_current_job().id
        )
        db.logger.debug(
            "rq: Received Queue Length: %d (%s)", len(q), ", ".join(q.job_ids)
        )
    except AttributeError:
        db.logger.debug("Debug worker_function called synchronously")

    exp = Experiment(session)
    key = "-----"

    exp.log(
        "Received an {} notification for assignment {}, participant {}".format(
            event_type, assignment_id, participant_id
        ),
        key,
    )

    if event_type == "TrackingEvent":
        node = None
        if node_id:
            node = models.Node.query.get(node_id)
        if not node:
            participant = None
            if participant_id:
                # Lookup assignment_id to create notifications
                participant = models.Participant.query.get(participant_id)
            elif assignment_id:
                participants = models.Participant.query.filter_by(
                    assignment_id=assignment_id
                ).all()
                # if there are one or more participants select the most recent
                if participants:
                    participant = max(participants, key=attrgetter("creation_time"))
                    participant_id = participant.id
            if not participant:
                exp.log(
                    "Warning: No participant associated with this "
                    "TrackingEvent notification.",
                    key,
                )
                return
            nodes = participant.nodes()
            if not nodes:
                exp.log(
                    "Warning: No node associated with this "
                    "TrackingEvent notification.",
                    key,
                )
                return
            node = max(nodes, key=attrgetter("creation_time"))

        if not details:
            details = {}
        info = information.TrackingEvent(origin=node, details=details)
        session.add(info)
        session.commit()
        return

    runner_cls = WorkerEvent.for_name(event_type)
    if not runner_cls:
        exp.log("Event type {} is not supported... ignoring.".format(event_type))
        return

    if assignment_id is not None:
        # save the notification to the notification table
        notif = models.Notification(assignment_id=assignment_id, event_type=event_type)
        session.add(notif)
        session.commit()

        # try to identify the participant
        participants = models.Participant.query.filter_by(
            assignment_id=assignment_id
        ).all()

        # if there are one or more participants select the most recent
        if participants:
            participant = max(participants, key=attrgetter("creation_time"))

        # if there are none print an error
        else:
            exp.log(
                "Warning: No participants associated with this "
                "assignment_id. Notification will not be processed.",
                key,
            )
            return None

    elif participant_id is not None:
        participant = models.Participant.query.filter_by(id=participant_id).all()[0]
    else:
        raise ValueError(
            "Error: worker_function needs either an assignment_id or a "
            "participant_id, they cannot both be None"
        )

    participant_id = participant.id

    runner = runner_cls(
        participant, assignment_id, exp, session, _config(), datetime.now()
    )
    runner()
    session.commit()

Response: This function is called by the worker thread when a new event is received.


Instruction:
How would you code a function in Python 3 to
capture a backup of the app.

Response:
def all_apps(self):
        """Capture a backup of the app."""
        cmd = ["heroku", "apps", "--json"]
        if self.team:
            cmd.extend(["--team", self.team])
        return json.loads(self._result(cmd))


Instruction:
How would you implement a function in Python 3 that
creates the heroku app and local git remote. Call this once you re getting the app and local git remote you re going to use.

Response:
def bootstrap(self):
        """Creates the heroku app and local git remote. Call this once you're
        in the local repo you're going to use.
        """
        cmd = ["heroku", "apps:create", self.name, "--buildpack", "heroku/python"]

        # If a team is specified, assign the app to the team.
        if self.team:
            cmd.extend(["--team", self.team])

        self._run(cmd)
        # Set HOST value
        self.set_multiple(
            HOST=self.url, CREATOR=self.login_name(), DALLINGER_UID=self.dallinger_uid
        )


Instruction:
Can you implement a function in Python 3 that
sets up an addon

Response:
def addon(self, name):
        """Set up an addon"""
        cmd = ["heroku", "addons:create", name, "--app", self.name]
        self._run(cmd)


Instruction:
Can you tell what is the following Python 3 function doing
def buildpack(self, url):
        cmd = ["heroku", "buildpacks:add", url, "--app", self.name]
        self._run(cmd)

Response: Add a buildpack by URL.


Instruction:
Make a summary of the following Python 3 code
def db_uri(self):
        output = self.get("DATABASE", subcommand="pg:credentials:url")
        match = re.search("(postgres://.*)$", output)
        if match is None:
            raise NameError(
                "Could not retrieve the DB URI. Check for error output from "
                "heroku above the stack trace."
            )
        return match.group(1)

Response: The connection URL for the remote database. For example postgres://some - long - uid@ec2 - 52 - 7 - 232 - 59. compute - 1. amazonaws. com : 5336. compute - 1. amazonaws. com


Instruction:
Create a Python 3 function for
destroying an app and all its add -ons

Response:
def destroy(self):
        """Destroy an app and all its add-ons"""
        result = self._result(
            ["heroku", "apps:destroy", "--app", self.name, "--confirm", self.name]
        )
        return result


Instruction:
How would you implement a function in Python 3 that
gets a app config value by name

Response:
def get(self, key, subcommand="config:get"):
        """Get a app config value by name"""
        cmd = ["heroku", subcommand, key, "--app", self.name]
        return self._result(cmd)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pg_wait(self):
        retries = 10
        while retries:
            retries = retries - 1
            try:
                self._run(["heroku", "pg:wait", "--app", self.name])
            except subprocess.CalledProcessError:
                time.sleep(5)
                if not retries:
                    raise
            else:
                break

Response: Wait for the DB to be fired up.


Instruction:
Explain what the following Python 3 code does
def restore(self, url):
        self._run(
            [
                "heroku",
                "pg:backups:restore",
                "{}".format(url),
                "DATABASE_URL",
                "--app",
                self.name,
                "--confirm",
                self.name,
            ]
        )

Response: Restore the remote database from the URL of a backup.


Instruction:
Can you tell what is the following Python 3 function doing
def scale_up_dyno(self, process, quantity, size):
        self._run(
            [
                "heroku",
                "ps:scale",
                "{}={}:{}".format(process, quantity, size),
                "--app",
                self.name,
            ]
        )

Response: Scale up a dyno.


Instruction:
Can you write a function in Python 3 where it
turns off web and worker dynos plus clock process.

Response:
def scale_down_dynos(self):
        """Turn off web and worker dynos, plus clock process if
        there is one and it's active.
        """
        processes = ["web", "worker"]
        if self.clock_is_on:
            processes.append("clock")
        for process in processes:
            self.scale_down_dyno(process)


Instruction:
How would you implement a function in Python 3 that
configures an app key value pair

Response:
def set(self, key, value):
        """Configure an app key/value pair"""
        cmd = [
            "heroku",
            "config:set",
            "{}={}".format(key, quote(str(value))),
            "--app",
            self.name,
        ]
        if self._is_sensitive_key(key):
            self._run_quiet(cmd)
        else:
            self._run(cmd)


Instruction:
Explain what the following Python 3 code does
def set_multiple(self, **kwargs):
        quiet = False
        if not kwargs:
            return
        cmd = ["heroku", "config:set"]
        for k in sorted(kwargs):
            cmd.append("{}={}".format(k, quote(str(kwargs[k]))))
            if self._is_sensitive_key(k):
                quiet = True
        cmd.extend(["--app", self.name])
        if quiet:
            self._run_quiet(cmd)
        else:
            self._run(cmd)

Response: Configure multiple app key value pairs


Instruction:
Explain what the following Python 3 code does
def start(self, timeout_secs=60):

        def _handle_timeout(signum, frame):
            raise HerokuTimeoutError(
                "Failed to start after {} seconds.".format(timeout_secs, self._record)
            )

        if self.is_running:
            self.out.log("Local Heroku is already running.")
            return

        signal.signal(signal.SIGALRM, _handle_timeout)
        signal.alarm(timeout_secs)
        self._boot()
        try:
            success = self._verify_startup()
        finally:
            signal.alarm(0)

        if not success:
            self.stop(signal.SIGKILL)
            raise HerokuStartupError(
                "Failed to start for unknown reason: {}".format(self._record)
            )
        return True

Response: Start the heroku local subprocess group and verify that it has started successfully.


Instruction:
Write a Python 3 script for
stopping the heroku local subprocess and all of its children.

Response:
def stop(self, signal=None):
        """Stop the heroku local subprocess and all of its children.
        """
        signal = signal or self.int_signal
        self.out.log("Cleaning up local Heroku process...")
        if self._process is None:
            self.out.log("No local Heroku process was running.")
            return

        try:
            os.killpg(os.getpgid(self._process.pid), signal)
            self.out.log("Local Heroku process terminated.")
        except OSError:
            self.out.log("Local Heroku was already terminated.")
            self.out.log(traceback.format_exc())
        finally:
            self._process = None


Instruction:
Given the following Python 3 function, write the documentation
def monitor(self, listener):
        for line in self._stream():
            self._record.append(line)
            if self.verbose:
                self.out.blather(line)
            if listener(line) is self.MONITOR_STOP:
                return

Response: Relay the stream to listener until stop.


Instruction:
How would you explain what the following Python 3 function does
def load():
    initialize_experiment_package(os.getcwd())
    try:
        try:
            from dallinger_experiment import experiment
        except ImportError:
            from dallinger_experiment import dallinger_experiment as experiment

        classes = inspect.getmembers(experiment, inspect.isclass)
        for name, c in classes:
            if "Experiment" in c.__bases__[0].__name__:
                return c
        else:
            raise ImportError
    except ImportError:
        logger.error("Could not import experiment.")
        raise

Response: Load the active experiment.


Instruction:
How would you code a function in Python 3 to
create the networks if they don t already exist.

Response:
def setup(self):
        """Create the networks if they don't already exist."""
        if not self.networks():
            for _ in range(self.practice_repeats):
                network = self.create_network()
                network.role = "practice"
                self.session.add(network)
            for _ in range(self.experiment_repeats):
                network = self.create_network()
                network.role = "experiment"
                self.session.add(network)
            self.session.commit()


Instruction:
How would you explain what the following Python 3 function does
def networks(self, role="all", full="all"):
        if full not in ["all", True, False]:
            raise ValueError(
                "full must be boolean or all, it cannot be {}".format(full)
            )

        if full == "all":
            if role == "all":
                return Network.query.all()
            else:
                return Network.query.filter_by(role=role).all()
        else:
            if role == "all":
                return Network.query.filter_by(full=full).all()
            else:
                return Network.query.filter(
                    and_(Network.role == role, Network.full == full)
                ).all()

Response: All the networks in the experiment.


Instruction:
Explain what the following Python 3 code does
def get_network_for_participant(self, participant):
        key = participant.id
        networks_with_space = (
            Network.query.filter_by(full=False).order_by(Network.id).all()
        )
        networks_participated_in = [
            node.network_id
            for node in Node.query.with_entities(Node.network_id)
            .filter_by(participant_id=participant.id)
            .all()
        ]

        legal_networks = [
            net for net in networks_with_space if net.id not in networks_participated_in
        ]

        if not legal_networks:
            self.log("No networks available, returning None", key)
            return None

        self.log(
            "{} networks out of {} available".format(
                len(legal_networks), (self.practice_repeats + self.experiment_repeats)
            ),
            key,
        )

        legal_practice_networks = [
            net for net in legal_networks if net.role == "practice"
        ]
        if legal_practice_networks:
            chosen_network = legal_practice_networks[0]
            self.log(
                "Practice networks available."
                "Assigning participant to practice network {}.".format(
                    chosen_network.id
                ),
                key,
            )
        else:
            chosen_network = self.choose_network(legal_networks, participant)
            self.log(
                "No practice networks available."
                "Assigning participant to experiment network {}".format(
                    chosen_network.id
                ),
                key,
            )
        return chosen_network

Response: Find a network for a participant.


Instruction:
Make a summary of the following Python 3 code
def recruit(self):
        if not self.networks(full=False):
            self.log("All networks full: closing recruitment", "-----")
            self.recruiter.close_recruitment()

Response: Recruit participants to the experiment as needed.


Instruction:
Given the following Python 3 function, write the documentation
def log_summary(self):
        participants = Participant.query.with_entities(Participant.status).all()
        counts = Counter([p.status for p in participants])
        sorted_counts = sorted(counts.items(), key=itemgetter(0))
        self.log("Status summary: {}".format(str(sorted_counts)))
        return sorted_counts

Response: Log a summary of all the participants status codes.


Instruction:
Explain what the following Python 3 code does
def save(self, *objects):
        if len(objects) > 0:
            self.session.add_all(objects)
        self.session.commit()

Response: Add all the objects to the session and commit them.


Instruction:
Can you generate the documentation for the following Python 3 function
def fail_participant(self, participant):
        participant_nodes = Node.query.filter_by(
            participant_id=participant.id, failed=False
        ).all()

        for node in participant_nodes:
            node.fail()

Response: Fail all the nodes of a participant.


Instruction:
Implement a Python 3 function for
deploying and run an experiment.

Response:
def run(self, exp_config=None, app_id=None, bot=False, **kwargs):
        """Deploy and run an experiment.

        The exp_config object is either a dictionary or a
        ``localconfig.LocalConfig`` object with parameters
        specific to the experiment run grouped by section.
        """
        import dallinger as dlgr

        app_id = self.make_uuid(app_id)

        if bot:
            kwargs["recruiter"] = "bots"

        self.app_id = app_id
        self.exp_config = exp_config or kwargs
        self.update_status("Starting")
        try:
            if self.exp_config.get("mode") == "debug":
                dlgr.command_line.debug.callback(
                    verbose=True, bot=bot, proxy=None, exp_config=self.exp_config
                )
            else:
                dlgr.deployment.deploy_sandbox_shared_setup(
                    dlgr.command_line.log,
                    app=app_id,
                    verbose=self.verbose,
                    exp_config=self.exp_config,
                )
        except Exception:
            self.update_status("Errored")
            raise
        else:
            self.update_status("Running")
        self._await_completion()
        self.update_status("Retrieving data")
        data = self.retrieve_data()
        self.update_status("Completed")
        return data


Instruction:
Write a Python 3 function for
collecting data for the provided experiment id.

Response:
def collect(self, app_id, exp_config=None, bot=False, **kwargs):
        """Collect data for the provided experiment id.

        The ``app_id`` parameter must be a valid UUID.
        If an existing data file is found for the UUID it will
        be returned, otherwise - if the UUID is not already registered -
        the experiment will be run and data collected.

        See :meth:`~Experiment.run` method for other parameters.
        """
        try:
            results = data_load(app_id)
            self.log(
                "Data found for experiment {}, retrieving.".format(app_id),
                key="Retrieve:",
            )
            return results
        except IOError:
            self.log(
                "Could not fetch data for id: {}, checking registry".format(app_id),
                key="Retrieve:",
            )

        exp_config = exp_config or {}
        if is_registered(app_id):
            raise RuntimeError(
                "The id {} is registered, ".format(app_id)
                + "but you do not have permission to access to the data"
            )
        elif kwargs.get("mode") == "debug" or exp_config.get("mode") == "debug":
            raise RuntimeError("No remote or local data found for id {}".format(app_id))

        try:
            assert isinstance(uuid.UUID(app_id, version=4), uuid.UUID)
        except (ValueError, AssertionError):
            raise ValueError("Invalid UUID supplied {}".format(app_id))

        self.log(
            "{} appears to be a new experiment id, running experiment.".format(app_id),
            key="Retrieve:",
        )
        return self.run(exp_config, app_id, bot, **kwargs)


Instruction:
Implement a function in Python 3 to
generate a new UUID.

Response:
def make_uuid(cls, app_id=None):
        """Generates a new UUID.
        This is a class method and can be called as `Experiment.make_uuid()`.
        Takes an optional `app_id` which is converted to a string and, if it
        is a valid UUID, returned.
        """
        try:
            if app_id and isinstance(uuid.UUID(str(app_id), version=4), uuid.UUID):
                return str(app_id)
        except (ValueError, AssertionError):
            pass
        return str(uuid.UUID(int=random.getrandbits(128)))