_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q13200
MTurkService.get_qualification_type_by_name
train
def get_qualification_type_by_name(self, name): """Return a Qualification Type by name. If the provided name matches more than one Qualification, check to see if any of the results match the provided name exactly. If there's an exact match, return that Qualification. Otherwise, raise an ...
python
{ "resource": "" }
q13201
MTurkService.assign_qualification
train
def assign_qualification(self, qualification_id, worker_id, score, notify=False): """Score a worker for a specific qualification""" return self._is_ok( self.mturk.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, ...
python
{ "resource": "" }
q13202
MTurkService.increment_qualification_score
train
def increment_qualification_score(self, name, worker_id, notify=False): """Increment the current qualification score for a worker, on a qualification with the provided name. """ result = self.get_current_qualification_score(name, worker_id) current_score = result["score"] or 0 ...
python
{ "resource": "" }
q13203
MTurkService.get_qualification_score
train
def get_qualification_score(self, qualification_id, worker_id): """Return a worker's qualification score as an iteger. """ try: response = self.mturk.get_qualification_score( QualificationTypeId=qualification_id, WorkerId=worker_id ) except ClientE...
python
{ "resource": "" }
q13204
MTurkService.get_current_qualification_score
train
def get_current_qualification_score(self, name, worker_id): """Return the current score for a worker, on a qualification with the provided name. """ qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( ...
python
{ "resource": "" }
q13205
MTurkService.dispose_qualification_type
train
def dispose_qualification_type(self, qualification_id): """Remove a qualification type we created""" return self._is_ok( self.mturk.delete_qualification_type(QualificationTypeId=qualification_id) )
python
{ "resource": "" }
q13206
MTurkService.get_workers_with_qualification
train
def get_workers_with_qualification(self, qualification_id): """Get workers with the given qualification.""" done = False next_token = None while not done: if next_token is not None: response = self.mturk.list_workers_with_qualification_type( ...
python
{ "resource": "" }
q13207
MTurkService.create_hit
train
def create_hit( self, title, description, keywords, reward, duration_hours, lifetime_days, ad_url, notification_url, approve_requirement, max_assignments, us_only, blacklist=None, annotation=None, ): ...
python
{ "resource": "" }
q13208
MTurkService.extend_hit
train
def extend_hit(self, hit_id, number, duration_hours=None): """Extend an existing HIT and return an updated description""" self.create_additional_assignments_for_hit(hit_id, number) if duration_hours is not None: self.update_expiration_for_hit(hit_id, duration_hours) return ...
python
{ "resource": "" }
q13209
MTurkService.expire_hit
train
def expire_hit(self, hit_id): """Expire a HIT, which will change its status to "Reviewable", allowing it to be deleted. """ try: self.mturk.update_expiration_for_hit(HITId=hit_id, ExpireAt=0) except Exception as ex: raise MTurkServiceException( ...
python
{ "resource": "" }
q13210
MTurkService.grant_bonus
train
def grant_bonus(self, assignment_id, amount, reason): """Grant a bonus to the MTurk Worker. Issues a payment of money from your account to a Worker. To be eligible for a bonus, the Worker must have submitted results for one of your HITs, and have had those results approved or re...
python
{ "resource": "" }
q13211
MTurkService.get_assignment
train
def get_assignment(self, assignment_id): """Get an assignment by ID and reformat the response. """ try: response = self.mturk.get_assignment(AssignmentId=assignment_id) except ClientError as ex: if "does not exist" in str(ex): return None ...
python
{ "resource": "" }
q13212
initialize_experiment_package
train
def initialize_experiment_package(path): """Make the specified directory importable as the `dallinger_experiment` package.""" # Create __init__.py if it doesn't exist (needed for Python 2) init_py = os.path.join(path, "__init__.py") if not os.path.exists(init_py): open(init_py, "a").close() ...
python
{ "resource": "" }
q13213
Participant.questions
train
def questions(self, type=None): """Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class. """ if type is None: type = Question if not issubclass(type, Question): ...
python
{ "resource": "" }
q13214
Participant.infos
train
def infos(self, type=None, failed=False): """Get all infos created by the participants nodes. Return a list of infos produced by nodes associated with the participant. If specified, ``type`` filters by class. By default, failed infos are excluded, to include only failed nodes use ``fail...
python
{ "resource": "" }
q13215
Question.json_data
train
def json_data(self): """Return json description of a question.""" return { "number": self.number, "type": self.type, "participant_id": self.participant_id, "question": self.question, "response": self.response, }
python
{ "resource": "" }
q13216
Network.nodes
train
def nodes(self, type=None, failed=False, participant_id=None): """Get nodes in the network. type specifies the type of Node. Failed can be "all", False (default) or True. If a participant_id is passed only nodes with that participant_id will be returned. """ if type is N...
python
{ "resource": "" }
q13217
Network.size
train
def size(self, type=None, failed=False): """How many nodes in a network. type specifies the class of node, failed can be True/False/all. """ return len(self.nodes(type=type, failed=failed))
python
{ "resource": "" }
q13218
Network.infos
train
def infos(self, type=None, failed=False): """ Get infos in the network. type specifies the type of info (defaults to Info). failed { False, True, "all" } specifies the failed state of the infos. To get infos from a specific node, see the infos() method in class :class:`~...
python
{ "resource": "" }
q13219
Network.transmissions
train
def transmissions(self, status="all", failed=False): """Get transmissions in the network. status { "all", "received", "pending" } failed { False, True, "all" } To get transmissions from a specific vector, see the transmissions() method in class Vector. """ if sta...
python
{ "resource": "" }
q13220
Network.vectors
train
def vectors(self, failed=False): """ Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors(). """ if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".f...
python
{ "resource": "" }
q13221
Node.neighbors
train
def neighbors(self, type=None, direction="to", failed=None): """Get a node's neighbors - nodes that are directly connected to it. Type specifies the class of neighbour and must be a subclass of Node (default is Node). Connection is the direction of the connections and can be "to" ...
python
{ "resource": "" }
q13222
Node.infos
train
def infos(self, type=None, failed=False): """Get infos that originate from this node. Type must be a subclass of :class:`~dallinger.models.Info`, the default is ``Info``. Failed can be True, False or "all". """ if type is None: type = Info if not issubclass...
python
{ "resource": "" }
q13223
Node.received_infos
train
def received_infos(self, type=None, failed=None): """Get infos that have been sent to this node. Type must be a subclass of info, the default is Info. """ if failed is not None: raise ValueError( "You should not pass a failed argument to received_infos. " ...
python
{ "resource": "" }
q13224
Node.transformations
train
def transformations(self, type=None, failed=False): """ Get Transformations done by this Node. type must be a type of Transformation (defaults to Transformation) Failed can be True, False or "all" """ if failed not in ["all", False, True]: raise ValueError("{...
python
{ "resource": "" }
q13225
Node.fail
train
def fail(self): """ Fail a node, setting its status to "failed". Also fails all vectors that connect to or from the node. You cannot fail a node that has already failed, but you can fail a dead node. Set node.failed to True and :attr:`~dallinger.models.Node.time_of_deat...
python
{ "resource": "" }
q13226
Vector.fail
train
def fail(self): """Fail a vector.""" if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() for t in self.transmissions(): t.fail...
python
{ "resource": "" }
q13227
Info.json_data
train
def json_data(self): """The json representation of an info.""" return { "type": self.type, "origin_id": self.origin_id, "network_id": self.network_id, "contents": self.contents, }
python
{ "resource": "" }
q13228
Info.transformations
train
def transformations(self, relationship="all"): """Get all the transformations of this info. Return a list of transformations involving this info. ``relationship`` can be "parent" (in which case only transformations where the info is the ``info_in`` are returned), "child" (in which case ...
python
{ "resource": "" }
q13229
Transmission.json_data
train
def json_data(self): """The json representation of a transmissions.""" return { "vector_id": self.vector_id, "origin_id": self.origin_id, "destination_id": self.destination_id, "info_id": self.info_id, "network_id": self.network_id, ...
python
{ "resource": "" }
q13230
Transformation.json_data
train
def json_data(self): """The json representation of a transformation.""" return { "info_in_id": self.info_in_id, "info_out_id": self.info_out_id, "node_id": self.node_id, "network_id": self.network_id, }
python
{ "resource": "" }
q13231
generate_random_id
train
def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits): """Generate random id numbers.""" return "".join(random.choice(chars) for x in range(size))
python
{ "resource": "" }
q13232
report_idle_after
train
def report_idle_after(seconds): """Report_idle_after after certain number of seconds.""" def decorator(func): def wrapper(*args, **kwargs): def _handle_timeout(signum, frame): config = get_config() if not config.ready: config.load() ...
python
{ "resource": "" }
q13233
verify_id
train
def verify_id(ctx, param, app): """Verify the experiment id.""" if app is None: raise TypeError("Select an experiment using the --app parameter.") elif app[0:5] == "dlgr-": raise ValueError( "The --app parameter requires the full " "UUID beginning with {}-...".format(...
python
{ "resource": "" }
q13234
verify_package
train
def verify_package(verbose=True): """Perform a series of checks on the current directory to verify that it's a valid Dallinger experiment. """ results = ( verify_directory(verbose), verify_experiment_module(verbose), verify_config(verbose), verify_no_conflicts(verbose), ...
python
{ "resource": "" }
q13235
require_exp_directory
train
def require_exp_directory(f): """Decorator to verify that a command is run inside a valid Dallinger experiment directory. """ error = "The current directory is not a valid Dallinger experiment." @wraps(f) def wrapper(**kwargs): if not verify_directory(kwargs.get("verbose")): ...
python
{ "resource": "" }
q13236
dallinger
train
def dallinger(): """Dallinger command-line utility.""" from logging.config import fileConfig fileConfig( os.path.join(os.path.dirname(__file__), "logging.ini"), disable_existing_loggers=False, )
python
{ "resource": "" }
q13237
qualify
train
def qualify(workers, qualification, value, by_name, notify, sandbox): """Assign a qualification to 1 or more workers""" if not (workers and qualification and value): raise click.BadParameter( "Must specify a qualification ID, value/score, and at least one worker ID" ) mturk = _mt...
python
{ "resource": "" }
q13238
revoke
train
def revoke(workers, qualification, by_name, reason, sandbox): """Revoke a qualification from 1 or more workers""" if not (workers and qualification): raise click.BadParameter( "Must specify a qualification ID or name, and at least one worker ID" ) mturk = _mturk_service_from_con...
python
{ "resource": "" }
q13239
hits
train
def hits(app, sandbox): """List hits for an experiment id.""" hit_list = list(_current_hits(_mturk_service_from_config(sandbox), app)) out = Output() out.log( "Found {} hits for this experiment id: {}".format( len(hit_list), ", ".join(h["id"] for h in hit_list) ) )
python
{ "resource": "" }
q13240
expire
train
def expire(app, sandbox, exit=True): """Expire hits for an experiment id.""" success = [] failures = [] service = _mturk_service_from_config(sandbox) hits = _current_hits(service, app) for hit in hits: hit_id = hit["id"] try: service.expire_hit(hit_id) suc...
python
{ "resource": "" }
q13241
destroy
train
def destroy(ctx, app, expire_hit, sandbox): """Tear down an experiment server.""" if expire_hit: ctx.invoke(expire, app=app, sandbox=sandbox, exit=False) HerokuApp(app).destroy()
python
{ "resource": "" }
q13242
monitor
train
def monitor(app): """Set up application monitoring.""" heroku_app = HerokuApp(dallinger_uid=app) webbrowser.open(heroku_app.dashboard_url) webbrowser.open("https://requester.mturk.com/mturk/manageHITs") heroku_app.open_logs() check_call(["open", heroku_app.db_uri]) while _keep_running(): ...
python
{ "resource": "" }
q13243
bot
train
def bot(app, debug): """Run the experiment bot.""" if debug is None: verify_id(None, None, app) (id, tmp) = setup_experiment(log) if debug: url = debug else: heroku_app = HerokuApp(dallinger_uid=app) worker = generate_random_id() hit = generate_random_id() ...
python
{ "resource": "" }
q13244
getdrawings
train
def getdrawings(): """Get all the drawings.""" infos = Info.query.all() sketches = [json.loads(info.contents) for info in infos] return jsonify(drawings=sketches)
python
{ "resource": "" }
q13245
inject_experiment
train
def inject_experiment(): """Inject experiment and enviroment variables into the template context.""" exp = Experiment(session) return dict(experiment=exp, env=os.environ)
python
{ "resource": "" }
q13246
consent
train
def consent(): """Return the consent form. Here for backwards-compatibility with 2.x.""" config = _config() return render_template( "consent.html", hit_id=request.args["hit_id"], assignment_id=request.args["assignment_id"], worker_id=request.args["worker_id"], mode=co...
python
{ "resource": "" }
q13247
request_parameter
train
def request_parameter(parameter, parameter_type=None, default=None, optional=False): """Get a parameter from a request. parameter is the name of the parameter you are looking for parameter_type is the type the parameter should have default is the value the parameter takes if it has not been passed ...
python
{ "resource": "" }
q13248
node_vectors
train
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="...
python
{ "resource": "" }
q13249
node_received_infos
train
def node_received_infos(node_id): """Get all the infos a node has been sent and has received. You must specify the node id in the url. You can also pass the info type. """ exp = Experiment(session) # get the parameters info_type = request_parameter( parameter="info_type", parameter...
python
{ "resource": "" }
q13250
tracking_event_post
train
def tracking_event_post(node_id): """Enqueue a TrackingEvent worker for the specified Node. """ details = request_parameter(parameter="details", optional=True) if details: details = loads(details) # check the node exists node = models.Node.query.get(node_id) if node is None: ...
python
{ "resource": "" }
q13251
info_post
train
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 t...
python
{ "resource": "" }
q13252
node_transmissions
train
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(p...
python
{ "resource": "" }
q13253
check_for_duplicate_assignments
train
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 = [ ...
python
{ "resource": "" }
q13254
worker_failed
train
def worker_failed(): """Fail worker. Used by bots only for now.""" 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(parti...
python
{ "resource": "" }
q13255
HerokuInfo.all_apps
train
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))
python
{ "resource": "" }
q13256
HerokuApp.bootstrap
train
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....
python
{ "resource": "" }
q13257
HerokuApp.addon
train
def addon(self, name): """Set up an addon""" cmd = ["heroku", "addons:create", name, "--app", self.name] self._run(cmd)
python
{ "resource": "" }
q13258
HerokuApp.addon_destroy
train
def addon_destroy(self, name): """Destroy an addon""" self._run( [ "heroku", "addons:destroy", name, "--app", self.name, "--confirm", self.name, ] )
python
{ "resource": "" }
q13259
HerokuApp.buildpack
train
def buildpack(self, url): """Add a buildpack by URL.""" cmd = ["heroku", "buildpacks:add", url, "--app", self.name] self._run(cmd)
python
{ "resource": "" }
q13260
HerokuApp.destroy
train
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
python
{ "resource": "" }
q13261
HerokuApp.get
train
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)
python
{ "resource": "" }
q13262
HerokuApp.pg_wait
train
def pg_wait(self): """Wait for the DB to be fired up.""" retries = 10 while retries: retries = retries - 1 try: self._run(["heroku", "pg:wait", "--app", self.name]) except subprocess.CalledProcessError: time.sleep(5) ...
python
{ "resource": "" }
q13263
HerokuApp.restore
train
def restore(self, url): """Restore the remote database from the URL of a backup.""" self._run( [ "heroku", "pg:backups:restore", "{}".format(url), "DATABASE_URL", "--app", self.name, ...
python
{ "resource": "" }
q13264
HerokuApp.scale_up_dyno
train
def scale_up_dyno(self, process, quantity, size): """Scale up a dyno.""" self._run( [ "heroku", "ps:scale", "{}={}:{}".format(process, quantity, size), "--app", self.name, ] )
python
{ "resource": "" }
q13265
HerokuApp.scale_down_dynos
train
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(proces...
python
{ "resource": "" }
q13266
HerokuLocalWrapper.start
train
def start(self, timeout_secs=60): """Start the heroku local subprocess group and verify that it has started successfully. The subprocess output is checked for a line matching 'success_regex' to indicate success. If no match is seen after 'timeout_secs', a HerokuTimeoutError is r...
python
{ "resource": "" }
q13267
HerokuLocalWrapper.stop
train
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.") ...
python
{ "resource": "" }
q13268
HerokuLocalWrapper.monitor
train
def monitor(self, listener): """Relay the stream to listener until told to stop. """ for line in self._stream(): self._record.append(line) if self.verbose: self.out.blather(line) if listener(line) is self.MONITOR_STOP: return
python
{ "resource": "" }
q13269
load
train
def load(): """Load the active experiment.""" 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...
python
{ "resource": "" }
q13270
Experiment.setup
train
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 rang...
python
{ "resource": "" }
q13271
Experiment.networks
train
def networks(self, role="all", full="all"): """All the networks in the experiment.""" 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": ...
python
{ "resource": "" }
q13272
Experiment.get_network_for_participant
train
def get_network_for_participant(self, participant): """Find a network for a participant. If no networks are available, None will be returned. By default participants can participate only once in each network and participants first complete networks with `role="practice"` before doing al...
python
{ "resource": "" }
q13273
Experiment.recruit
train
def recruit(self): """Recruit participants to the experiment as needed. This method runs whenever a participant successfully completes the experiment (participants who fail to finish successfully are automatically replaced). By default it recruits 1 participant at a time until a...
python
{ "resource": "" }
q13274
Experiment.log_summary
train
def log_summary(self): """Log a summary of all the participants' status codes.""" 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...
python
{ "resource": "" }
q13275
Experiment.save
train
def save(self, *objects): """Add all the objects to the session and commit them. This only needs to be done for networks and participants. """ if len(objects) > 0: self.session.add_all(objects) self.session.commit()
python
{ "resource": "" }
q13276
Experiment.fail_participant
train
def fail_participant(self, participant): """Fail all the nodes of a participant.""" participant_nodes = Node.query.filter_by( participant_id=participant.id, failed=False ).all() for node in participant_nodes: node.fail()
python
{ "resource": "" }
q13277
Experiment.run
train
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...
python
{ "resource": "" }
q13278
Experiment.collect
train
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 - ...
python
{ "resource": "" }
q13279
Experiment.retrieve_data
train
def retrieve_data(self): """Retrieves and saves data from a running experiment""" local = False if self.exp_config.get("mode") == "debug": local = True filename = export(self.app_id, local=local) logger.debug("Data exported to %s" % filename) return Data(filen...
python
{ "resource": "" }
q13280
Experiment.end_experiment
train
def end_experiment(self): """Terminates a running experiment""" if self.exp_config.get("mode") != "debug": HerokuApp(self.app_id).destroy() return True
python
{ "resource": "" }
q13281
Scrubber._ipython_display_
train
def _ipython_display_(self): """Display Jupyter Notebook widget""" from IPython.display import display self.build_widget() display(self.widget())
python
{ "resource": "" }
q13282
from_config
train
def from_config(config): """Return a Recruiter instance based on the configuration. Default is HotAirRecruiter in debug mode (unless we're using the bot recruiter, which can be used in debug mode) and the MTurkRecruiter in other modes. """ debug_mode = config.get("mode") == "debug" name = c...
python
{ "resource": "" }
q13283
CLIRecruiter.recruit
train
def recruit(self, n=1): """Generate experiemnt URLs and print them to the console.""" logger.info("Recruiting {} CLI participants".format(n)) urls = [] template = "{}/ad?recruiter={}&assignmentId={}&hitId={}&workerId={}&mode={}" for i in range(n): ad_url = template.fo...
python
{ "resource": "" }
q13284
CLIRecruiter.reward_bonus
train
def reward_bonus(self, assignment_id, amount, reason): """Print out bonus info for the assignment""" logger.info( 'Award ${} for assignment {}, with reason "{}"'.format( amount, assignment_id, reason ) )
python
{ "resource": "" }
q13285
SimulatedRecruiter.open_recruitment
train
def open_recruitment(self, n=1): """Open recruitment.""" logger.info("Opening Sim recruitment for {} participants".format(n)) return {"items": self.recruit(n), "message": "Simulated recruitment only"}
python
{ "resource": "" }
q13286
MTurkRecruiter.open_recruitment
train
def open_recruitment(self, n=1): """Open a connection to AWS MTurk and create a HIT.""" logger.info("Opening MTurk recruitment for {} participants".format(n)) if self.is_in_progress: raise MTurkRecruiterException( "Tried to open_recruitment on already open recruiter."...
python
{ "resource": "" }
q13287
MTurkRecruiter.recruit
train
def recruit(self, n=1): """Recruit n new participants to an existing HIT""" logger.info("Recruiting {} MTurk participants".format(n)) if not self.config.get("auto_recruit"): logger.info("auto_recruit is False: recruitment suppressed") return hit_id = self.current...
python
{ "resource": "" }
q13288
MTurkRecruiter.notify_completed
train
def notify_completed(self, participant): """Assign a Qualification to the Participant for the experiment ID, and for the configured group_name, if it's been set. Overrecruited participants don't receive qualifications, since they haven't actually completed the experiment. This allows th...
python
{ "resource": "" }
q13289
MTurkRecruiter.notify_duration_exceeded
train
def notify_duration_exceeded(self, participants, reference_time): """The participant has exceed the maximum time for the activity, defined in the "duration" config value. We need find out the assignment status on MTurk and act based on this. """ unsubmitted = [] for parti...
python
{ "resource": "" }
q13290
MTurkRecruiter.reward_bonus
train
def reward_bonus(self, assignment_id, amount, reason): """Reward the Turker for a specified assignment with a bonus.""" try: return self.mturkservice.grant_bonus(assignment_id, amount, reason) except MTurkServiceException as ex: logger.exception(str(ex))
python
{ "resource": "" }
q13291
MTurkRecruiter._create_mturk_qualifications
train
def _create_mturk_qualifications(self): """Create MTurk Qualification for experiment ID, and for group_name if it's been set. Qualifications with these names already exist, but it's faster to try and fail than to check, then try. """ for name, desc in self.qualifications.items():...
python
{ "resource": "" }
q13292
BotRecruiter.open_recruitment
train
def open_recruitment(self, n=1): """Start recruiting right away.""" logger.info("Opening Bot recruitment for {} participants".format(n)) factory = self._get_bot_factory() bot_class_name = factory("", "", "").__class__.__name__ return { "items": self.recruit(n), ...
python
{ "resource": "" }
q13293
BotRecruiter.recruit
train
def recruit(self, n=1): """Recruit n new participant bots to the queue""" logger.info("Recruiting {} Bot participants".format(n)) factory = self._get_bot_factory() urls = [] q = _get_queue() for _ in range(n): base_url = get_base_url() worker = gen...
python
{ "resource": "" }
q13294
BotRecruiter.notify_duration_exceeded
train
def notify_duration_exceeded(self, participants, reference_time): """The bot participant has been working longer than the time defined in the "duration" config value. """ for participant in participants: participant.status = "rejected" session.commit()
python
{ "resource": "" }
q13295
MultiRecruiter.parse_spec
train
def parse_spec(self): """Parse the specification of how to recruit participants. Example: recruiters = bots: 5, mturk: 1 """ recruiters = [] spec = get_config().get("recruiters") for match in self.SPEC_RE.finditer(spec): name = match.group(1) coun...
python
{ "resource": "" }
q13296
MultiRecruiter.recruiters
train
def recruiters(self, n=1): """Iterator that provides recruiters along with the participant count to be recruited for up to `n` participants. We use the `Recruitment` table in the db to keep track of how many recruitments have been requested using each recruiter. We'll use the fi...
python
{ "resource": "" }
q13297
MultiRecruiter.open_recruitment
train
def open_recruitment(self, n=1): """Return initial experiment URL list. """ logger.info("Multi recruitment running for {} participants".format(n)) recruitments = [] messages = {} remaining = n for recruiter, count in self.recruiters(n): if not count: ...
python
{ "resource": "" }
q13298
run_check
train
def run_check(participants, config, reference_time): """For each participant, if they've been active for longer than the experiment duration + 2 minutes, we take action. """ recruiters_with_late_participants = defaultdict(list) for p in participants: timeline = ParticipationTime(p, reference...
python
{ "resource": "" }
q13299
register
train
def register(dlgr_id, snapshot=None): """Register the experiment using configured services.""" try: config.get("osf_access_token") except KeyError: pass else: osf_id = _create_osf_project(dlgr_id) _upload_assets_to_OSF(dlgr_id, osf_id)
python
{ "resource": "" }