id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
13,200
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_qualification_type_by_name
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 exception. """ max_fuzzy_matches_to_check = 100 query = name.upper() start = time.time() args = { "Query": query, "MustBeRequestable": False, "MustBeOwnedByCaller": True, "MaxResults": max_fuzzy_matches_to_check, } results = self.mturk.list_qualification_types(**args)["QualificationTypes"] # This loop is largely for tests, because there's some indexing that # needs to happen on MTurk for search to work: while not results and time.time() - start < self.max_wait_secs: time.sleep(1) results = self.mturk.list_qualification_types(**args)["QualificationTypes"] if not results: return None qualifications = [self._translate_qtype(r) for r in results] if len(qualifications) > 1: for qualification in qualifications: if qualification["name"].upper() == query: return qualification raise MTurkServiceException("{} was not a unique name".format(query)) return qualifications[0]
python
def get_qualification_type_by_name(self, name): max_fuzzy_matches_to_check = 100 query = name.upper() start = time.time() args = { "Query": query, "MustBeRequestable": False, "MustBeOwnedByCaller": True, "MaxResults": max_fuzzy_matches_to_check, } results = self.mturk.list_qualification_types(**args)["QualificationTypes"] # This loop is largely for tests, because there's some indexing that # needs to happen on MTurk for search to work: while not results and time.time() - start < self.max_wait_secs: time.sleep(1) results = self.mturk.list_qualification_types(**args)["QualificationTypes"] if not results: return None qualifications = [self._translate_qtype(r) for r in results] if len(qualifications) > 1: for qualification in qualifications: if qualification["name"].upper() == query: return qualification raise MTurkServiceException("{} was not a unique name".format(query)) return qualifications[0]
[ "def", "get_qualification_type_by_name", "(", "self", ",", "name", ")", ":", "max_fuzzy_matches_to_check", "=", "100", "query", "=", "name", ".", "upper", "(", ")", "start", "=", "time", ".", "time", "(", ")", "args", "=", "{", "\"Query\"", ":", "query", ...
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 exception.
[ "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", ".", "I...
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L207-L240
13,201
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.assign_qualification
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, IntegerValue=score, SendNotification=notify, ) )
python
def assign_qualification(self, qualification_id, worker_id, score, notify=False): return self._is_ok( self.mturk.associate_qualification_with_worker( QualificationTypeId=qualification_id, WorkerId=worker_id, IntegerValue=score, SendNotification=notify, ) )
[ "def", "assign_qualification", "(", "self", ",", "qualification_id", ",", "worker_id", ",", "score", ",", "notify", "=", "False", ")", ":", "return", "self", ".", "_is_ok", "(", "self", ".", "mturk", ".", "associate_qualification_with_worker", "(", "Qualificatio...
Score a worker for a specific qualification
[ "Score", "a", "worker", "for", "a", "specific", "qualification" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L242-L251
13,202
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.increment_qualification_score
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 new_score = current_score + 1 qtype_id = result["qtype"]["id"] self.assign_qualification(qtype_id, worker_id, new_score, notify) return {"qtype": result["qtype"], "score": new_score}
python
def increment_qualification_score(self, name, worker_id, notify=False): result = self.get_current_qualification_score(name, worker_id) current_score = result["score"] or 0 new_score = current_score + 1 qtype_id = result["qtype"]["id"] self.assign_qualification(qtype_id, worker_id, new_score, notify) return {"qtype": result["qtype"], "score": new_score}
[ "def", "increment_qualification_score", "(", "self", ",", "name", ",", "worker_id", ",", "notify", "=", "False", ")", ":", "result", "=", "self", ".", "get_current_qualification_score", "(", "name", ",", "worker_id", ")", "current_score", "=", "result", "[", "...
Increment the current qualification score for a worker, on a qualification with the provided name.
[ "Increment", "the", "current", "qualification", "score", "for", "a", "worker", "on", "a", "qualification", "with", "the", "provided", "name", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L257-L267
13,203
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_qualification_score
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 ClientError as ex: error = str(ex) if "does not exist" in error: raise WorkerLacksQualification( "Worker {} does not have qualification {}.".format( worker_id, qualification_id ) ) if "operation can be called with a status of: Granted" in error: raise RevokedQualification( "Worker {} has had qualification {} revoked.".format( worker_id, qualification_id ) ) raise MTurkServiceException(error) return response["Qualification"]["IntegerValue"]
python
def get_qualification_score(self, qualification_id, worker_id): try: response = self.mturk.get_qualification_score( QualificationTypeId=qualification_id, WorkerId=worker_id ) except ClientError as ex: error = str(ex) if "does not exist" in error: raise WorkerLacksQualification( "Worker {} does not have qualification {}.".format( worker_id, qualification_id ) ) if "operation can be called with a status of: Granted" in error: raise RevokedQualification( "Worker {} has had qualification {} revoked.".format( worker_id, qualification_id ) ) raise MTurkServiceException(error) return response["Qualification"]["IntegerValue"]
[ "def", "get_qualification_score", "(", "self", ",", "qualification_id", ",", "worker_id", ")", ":", "try", ":", "response", "=", "self", ".", "mturk", ".", "get_qualification_score", "(", "QualificationTypeId", "=", "qualification_id", ",", "WorkerId", "=", "worke...
Return a worker's qualification score as an iteger.
[ "Return", "a", "worker", "s", "qualification", "score", "as", "an", "iteger", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L276-L299
13,204
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_current_qualification_score
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( 'No Qualification exists with name "{}"'.format(name) ) try: score = self.get_qualification_score(qtype["id"], worker_id) except (WorkerLacksQualification, RevokedQualification): score = None return {"qtype": qtype, "score": score}
python
def get_current_qualification_score(self, name, worker_id): qtype = self.get_qualification_type_by_name(name) if qtype is None: raise QualificationNotFoundException( 'No Qualification exists with name "{}"'.format(name) ) try: score = self.get_qualification_score(qtype["id"], worker_id) except (WorkerLacksQualification, RevokedQualification): score = None return {"qtype": qtype, "score": score}
[ "def", "get_current_qualification_score", "(", "self", ",", "name", ",", "worker_id", ")", ":", "qtype", "=", "self", ".", "get_qualification_type_by_name", "(", "name", ")", "if", "qtype", "is", "None", ":", "raise", "QualificationNotFoundException", "(", "'No Qu...
Return the current score for a worker, on a qualification with the provided name.
[ "Return", "the", "current", "score", "for", "a", "worker", "on", "a", "qualification", "with", "the", "provided", "name", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L301-L315
13,205
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.dispose_qualification_type
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
def dispose_qualification_type(self, qualification_id): return self._is_ok( self.mturk.delete_qualification_type(QualificationTypeId=qualification_id) )
[ "def", "dispose_qualification_type", "(", "self", ",", "qualification_id", ")", ":", "return", "self", ".", "_is_ok", "(", "self", ".", "mturk", ".", "delete_qualification_type", "(", "QualificationTypeId", "=", "qualification_id", ")", ")" ]
Remove a qualification type we created
[ "Remove", "a", "qualification", "type", "we", "created" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L317-L321
13,206
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_workers_with_qualification
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( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", NextToken=next_token, ) else: response = self.mturk.list_workers_with_qualification_type( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", ) if response: for r in response["Qualifications"]: yield {"id": r["WorkerId"], "score": r["IntegerValue"]} if "NextToken" in response: next_token = response["NextToken"] else: done = True
python
def get_workers_with_qualification(self, qualification_id): done = False next_token = None while not done: if next_token is not None: response = self.mturk.list_workers_with_qualification_type( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", NextToken=next_token, ) else: response = self.mturk.list_workers_with_qualification_type( QualificationTypeId=qualification_id, MaxResults=MAX_SUPPORTED_BATCH_SIZE, Status="Granted", ) if response: for r in response["Qualifications"]: yield {"id": r["WorkerId"], "score": r["IntegerValue"]} if "NextToken" in response: next_token = response["NextToken"] else: done = True
[ "def", "get_workers_with_qualification", "(", "self", ",", "qualification_id", ")", ":", "done", "=", "False", "next_token", "=", "None", "while", "not", "done", ":", "if", "next_token", "is", "not", "None", ":", "response", "=", "self", ".", "mturk", ".", ...
Get workers with the given qualification.
[ "Get", "workers", "with", "the", "given", "qualification", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L323-L347
13,207
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.create_hit
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, ): """Create the actual HIT and return a dict with its useful properties.""" frame_height = 600 mturk_question = self._external_question(ad_url, frame_height) qualifications = self.build_hit_qualifications( approve_requirement, us_only, blacklist ) # We need a HIT_Type in order to register for REST notifications hit_type_id = self.register_hit_type( title, description, reward, duration_hours, keywords, qualifications ) self.set_rest_notification(notification_url, hit_type_id) params = { "HITTypeId": hit_type_id, "Question": mturk_question, "LifetimeInSeconds": int( datetime.timedelta(days=lifetime_days).total_seconds() ), "MaxAssignments": max_assignments, "UniqueRequestToken": self._request_token(), } if annotation: params["RequesterAnnotation"] = annotation response = self.mturk.create_hit_with_hit_type(**params) if "HIT" not in response: raise MTurkServiceException("HIT request was invalid for unknown reason.") return self._translate_hit(response["HIT"])
python
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, ): frame_height = 600 mturk_question = self._external_question(ad_url, frame_height) qualifications = self.build_hit_qualifications( approve_requirement, us_only, blacklist ) # We need a HIT_Type in order to register for REST notifications hit_type_id = self.register_hit_type( title, description, reward, duration_hours, keywords, qualifications ) self.set_rest_notification(notification_url, hit_type_id) params = { "HITTypeId": hit_type_id, "Question": mturk_question, "LifetimeInSeconds": int( datetime.timedelta(days=lifetime_days).total_seconds() ), "MaxAssignments": max_assignments, "UniqueRequestToken": self._request_token(), } if annotation: params["RequesterAnnotation"] = annotation response = self.mturk.create_hit_with_hit_type(**params) if "HIT" not in response: raise MTurkServiceException("HIT request was invalid for unknown reason.") return self._translate_hit(response["HIT"])
[ "def", "create_hit", "(", "self", ",", "title", ",", "description", ",", "keywords", ",", "reward", ",", "duration_hours", ",", "lifetime_days", ",", "ad_url", ",", "notification_url", ",", "approve_requirement", ",", "max_assignments", ",", "us_only", ",", "bla...
Create the actual HIT and return a dict with its useful properties.
[ "Create", "the", "actual", "HIT", "and", "return", "a", "dict", "with", "its", "useful", "properties", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L349-L392
13,208
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.extend_hit
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 self.get_hit(hit_id)
python
def extend_hit(self, hit_id, number, duration_hours=None): 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 self.get_hit(hit_id)
[ "def", "extend_hit", "(", "self", ",", "hit_id", ",", "number", ",", "duration_hours", "=", "None", ")", ":", "self", ".", "create_additional_assignments_for_hit", "(", "hit_id", ",", "number", ")", "if", "duration_hours", "is", "not", "None", ":", "self", "...
Extend an existing HIT and return an updated description
[ "Extend", "an", "existing", "HIT", "and", "return", "an", "updated", "description" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L394-L401
13,209
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.expire_hit
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( "Failed to expire HIT {}: {}".format(hit_id, str(ex)) ) return True
python
def expire_hit(self, hit_id): try: self.mturk.update_expiration_for_hit(HITId=hit_id, ExpireAt=0) except Exception as ex: raise MTurkServiceException( "Failed to expire HIT {}: {}".format(hit_id, str(ex)) ) return True
[ "def", "expire_hit", "(", "self", ",", "hit_id", ")", ":", "try", ":", "self", ".", "mturk", ".", "update_expiration_for_hit", "(", "HITId", "=", "hit_id", ",", "ExpireAt", "=", "0", ")", "except", "Exception", "as", "ex", ":", "raise", "MTurkServiceExcept...
Expire a HIT, which will change its status to "Reviewable", allowing it to be deleted.
[ "Expire", "a", "HIT", "which", "will", "change", "its", "status", "to", "Reviewable", "allowing", "it", "to", "be", "deleted", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L442-L452
13,210
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.grant_bonus
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 rejected. This payment happens separately from the reward you pay to the Worker when you approve the Worker's assignment. """ assignment = self.get_assignment(assignment_id) worker_id = assignment["worker_id"] amount_str = "{:.2f}".format(amount) try: return self._is_ok( self.mturk.send_bonus( WorkerId=worker_id, BonusAmount=amount_str, AssignmentId=assignment_id, Reason=reason, UniqueRequestToken=self._request_token(), ) ) except ClientError as ex: error = "Failed to pay assignment {} bonus of {}: {}".format( assignment_id, amount_str, str(ex) ) raise MTurkServiceException(error)
python
def grant_bonus(self, assignment_id, amount, reason): assignment = self.get_assignment(assignment_id) worker_id = assignment["worker_id"] amount_str = "{:.2f}".format(amount) try: return self._is_ok( self.mturk.send_bonus( WorkerId=worker_id, BonusAmount=amount_str, AssignmentId=assignment_id, Reason=reason, UniqueRequestToken=self._request_token(), ) ) except ClientError as ex: error = "Failed to pay assignment {} bonus of {}: {}".format( assignment_id, amount_str, str(ex) ) raise MTurkServiceException(error)
[ "def", "grant_bonus", "(", "self", ",", "assignment_id", ",", "amount", ",", "reason", ")", ":", "assignment", "=", "self", ".", "get_assignment", "(", "assignment_id", ")", "worker_id", "=", "assignment", "[", "\"worker_id\"", "]", "amount_str", "=", "\"{:.2f...
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 rejected. This payment happens separately from the reward you pay to the Worker when you approve the Worker's assignment.
[ "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"...
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L476-L502
13,211
Dallinger/Dallinger
dallinger/mturk.py
MTurkService.get_assignment
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 raise return self._translate_assignment(response["Assignment"])
python
def get_assignment(self, assignment_id): try: response = self.mturk.get_assignment(AssignmentId=assignment_id) except ClientError as ex: if "does not exist" in str(ex): return None raise return self._translate_assignment(response["Assignment"])
[ "def", "get_assignment", "(", "self", ",", "assignment_id", ")", ":", "try", ":", "response", "=", "self", ".", "mturk", ".", "get_assignment", "(", "AssignmentId", "=", "assignment_id", ")", "except", "ClientError", "as", "ex", ":", "if", "\"does not exist\""...
Get an assignment by ID and reformat the response.
[ "Get", "an", "assignment", "by", "ID", "and", "reformat", "the", "response", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/mturk.py#L504-L513
13,212
Dallinger/Dallinger
dallinger/config.py
initialize_experiment_package
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() # Retain already set experiment module if sys.modules.get("dallinger_experiment") is not None: return dirname = os.path.dirname(path) basename = os.path.basename(path) sys.path.insert(0, dirname) package = __import__(basename) if path not in package.__path__: raise Exception("Package was not imported from the requested path!") sys.modules["dallinger_experiment"] = package package.__package__ = "dallinger_experiment" sys.path.pop(0)
python
def initialize_experiment_package(path): # 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() # Retain already set experiment module if sys.modules.get("dallinger_experiment") is not None: return dirname = os.path.dirname(path) basename = os.path.basename(path) sys.path.insert(0, dirname) package = __import__(basename) if path not in package.__path__: raise Exception("Package was not imported from the requested path!") sys.modules["dallinger_experiment"] = package package.__package__ = "dallinger_experiment" sys.path.pop(0)
[ "def", "initialize_experiment_package", "(", "path", ")", ":", "# 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", ...
Make the specified directory importable as the `dallinger_experiment` package.
[ "Make", "the", "specified", "directory", "importable", "as", "the", "dallinger_experiment", "package", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/config.py#L270-L288
13,213
Dallinger/Dallinger
dallinger/models.py
Participant.questions
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): raise TypeError("{} is not a valid question type.".format(type)) return type.query.filter_by(participant_id=self.id).all()
python
def questions(self, type=None): if type is None: type = Question if not issubclass(type, Question): raise TypeError("{} is not a valid question type.".format(type)) return type.query.filter_by(participant_id=self.id).all()
[ "def", "questions", "(", "self", ",", "type", "=", "None", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Question", "if", "not", "issubclass", "(", "type", ",", "Question", ")", ":", "raise", "TypeError", "(", "\"{} is not a valid question type....
Get questions associated with this participant. Return a list of questions associated with the participant. If specified, ``type`` filters by class.
[ "Get", "questions", "associated", "with", "this", "participant", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L217-L230
13,214
Dallinger/Dallinger
dallinger/models.py
Participant.infos
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 ``failed=True``, for all nodes use ``failed=all``. Note that failed filters the infos, not the nodes - infos from all nodes (whether failed or not) can be returned. """ nodes = self.nodes(failed="all") infos = [] for n in nodes: infos.extend(n.infos(type=type, failed=failed)) return infos
python
def infos(self, type=None, failed=False): nodes = self.nodes(failed="all") infos = [] for n in nodes: infos.extend(n.infos(type=type, failed=failed)) return infos
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "nodes", "=", "self", ".", "nodes", "(", "failed", "=", "\"all\"", ")", "infos", "=", "[", "]", "for", "n", "in", "nodes", ":", "infos", ".", "extend", ...
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 ``failed=True``, for all nodes use ``failed=all``. Note that failed filters the infos, not the nodes - infos from all nodes (whether failed or not) can be returned.
[ "Get", "all", "infos", "created", "by", "the", "participants", "nodes", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L232-L247
13,215
Dallinger/Dallinger
dallinger/models.py
Question.json_data
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
def json_data(self): return { "number": self.number, "type": self.type, "participant_id": self.participant_id, "question": self.question, "response": self.response, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"number\"", ":", "self", ".", "number", ",", "\"type\"", ":", "self", ".", "type", ",", "\"participant_id\"", ":", "self", ".", "participant_id", ",", "\"question\"", ":", "self", ".", "question",...
Return json description of a question.
[ "Return", "json", "description", "of", "a", "question", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L332-L340
13,216
Dallinger/Dallinger
dallinger/models.py
Network.nodes
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 None: type = Node if not issubclass(type, Node): raise TypeError("{} is not a valid node type.".format(type)) if failed not in ["all", False, True]: raise ValueError("{} is not a valid node failed".format(failed)) if participant_id is not None: if failed == "all": return type.query.filter_by( network_id=self.id, participant_id=participant_id ).all() else: return type.query.filter_by( network_id=self.id, participant_id=participant_id, failed=failed ).all() else: if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(failed=failed, network_id=self.id).all()
python
def nodes(self, type=None, failed=False, participant_id=None): if type is None: type = Node if not issubclass(type, Node): raise TypeError("{} is not a valid node type.".format(type)) if failed not in ["all", False, True]: raise ValueError("{} is not a valid node failed".format(failed)) if participant_id is not None: if failed == "all": return type.query.filter_by( network_id=self.id, participant_id=participant_id ).all() else: return type.query.filter_by( network_id=self.id, participant_id=participant_id, failed=failed ).all() else: if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(failed=failed, network_id=self.id).all()
[ "def", "nodes", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ",", "participant_id", "=", "None", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Node", "if", "not", "issubclass", "(", "type", ",", "Node", ")", ":", ...
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.
[ "Get", "nodes", "in", "the", "network", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L393-L422
13,217
Dallinger/Dallinger
dallinger/models.py
Network.size
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
def size(self, type=None, failed=False): return len(self.nodes(type=type, failed=failed))
[ "def", "size", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "return", "len", "(", "self", ".", "nodes", "(", "type", "=", "type", ",", "failed", "=", "failed", ")", ")" ]
How many nodes in a network. type specifies the class of node, failed can be True/False/all.
[ "How", "many", "nodes", "in", "a", "network", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L424-L430
13,218
Dallinger/Dallinger
dallinger/models.py
Network.infos
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:`~dallinger.models.Node`. """ if type is None: type = Info if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(network_id=self.id, failed=failed).all()
python
def infos(self, type=None, failed=False): if type is None: type = Info if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if failed == "all": return type.query.filter_by(network_id=self.id).all() else: return type.query.filter_by(network_id=self.id, failed=failed).all()
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Info", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueE...
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:`~dallinger.models.Node`.
[ "Get", "infos", "in", "the", "network", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L432-L450
13,219
Dallinger/Dallinger
dallinger/models.py
Network.transmissions
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 status not in ["all", "pending", "received"]: raise ValueError( "You cannot get transmission of status {}.".format(status) + "Status can only be pending, received or all" ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if status == "all": if failed == "all": return Transmission.query.filter_by(network_id=self.id).all() else: return Transmission.query.filter_by( network_id=self.id, failed=failed ).all() else: if failed == "all": return Transmission.query.filter_by( network_id=self.id, status=status ).all() else: return Transmission.query.filter_by( network_id=self.id, status=status, failed=failed ).all()
python
def transmissions(self, status="all", failed=False): if status not in ["all", "pending", "received"]: raise ValueError( "You cannot get transmission of status {}.".format(status) + "Status can only be pending, received or all" ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid failed".format(failed)) if status == "all": if failed == "all": return Transmission.query.filter_by(network_id=self.id).all() else: return Transmission.query.filter_by( network_id=self.id, failed=failed ).all() else: if failed == "all": return Transmission.query.filter_by( network_id=self.id, status=status ).all() else: return Transmission.query.filter_by( network_id=self.id, status=status, failed=failed ).all()
[ "def", "transmissions", "(", "self", ",", "status", "=", "\"all\"", ",", "failed", "=", "False", ")", ":", "if", "status", "not", "in", "[", "\"all\"", ",", "\"pending\"", ",", "\"received\"", "]", ":", "raise", "ValueError", "(", "\"You cannot get transmiss...
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.
[ "Get", "transmissions", "in", "the", "network", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L452-L483
13,220
Dallinger/Dallinger
dallinger/models.py
Network.vectors
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".format(failed)) if failed == "all": return Vector.query.filter_by(network_id=self.id).all() else: return Vector.query.filter_by(network_id=self.id, failed=failed).all()
python
def vectors(self, failed=False): if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".format(failed)) if failed == "all": return Vector.query.filter_by(network_id=self.id).all() else: return Vector.query.filter_by(network_id=self.id, failed=failed).all()
[ "def", "vectors", "(", "self", ",", "failed", "=", "False", ")", ":", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueError", "(", "\"{} is not a valid vector failed\"", ".", "format", "(", "failed", ")", ...
Get vectors in the network. failed = { False, True, "all" } To get the vectors to/from to a specific node, see Node.vectors().
[ "Get", "vectors", "in", "the", "network", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L519-L532
13,221
Dallinger/Dallinger
dallinger/models.py
Node.neighbors
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" (default), "from", "either", or "both". """ # get type if type is None: type = Node if not issubclass(type, Node): raise ValueError( "{} is not a valid neighbor type," "needs to be a subclass of Node.".format(type) ) # get direction if direction not in ["both", "either", "from", "to"]: raise ValueError( "{} not a valid neighbor connection." "Should be both, either, to or from.".format(direction) ) if failed is not None: raise ValueError( "You should not pass a failed argument to neighbors(). " "Neighbors is " "unusual in that a failed argument cannot be passed. This is " "because there is inherent uncertainty in what it means for a " "neighbor to be failed. The neighbors function will only ever " "return not-failed nodes connected to you via not-failed " "vectors. If you want to do more elaborate queries, for " "example, getting not-failed nodes connected to you via failed" " vectors, you should do so via sql queries." ) neighbors = [] # get the neighbours if direction == "to": outgoing_vectors = ( Vector.query.with_entities(Vector.destination_id) .filter_by(origin_id=self.id, failed=False) .all() ) neighbor_ids = [v.destination_id for v in outgoing_vectors] if neighbor_ids: neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all() neighbors = [n for n in neighbors if isinstance(n, type)] if direction == "from": incoming_vectors = ( Vector.query.with_entities(Vector.origin_id) .filter_by(destination_id=self.id, failed=False) .all() ) neighbor_ids = [v.origin_id for v in incoming_vectors] if neighbor_ids: neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all() neighbors = [n for n in neighbors if isinstance(n, type)] if direction == "either": neighbors = list( set( self.neighbors(type=type, direction="to") + self.neighbors(type=type, direction="from") ) ) if direction == "both": neighbors = list( set(self.neighbors(type=type, direction="to")) & set(self.neighbors(type=type, direction="from")) ) return neighbors
python
def neighbors(self, type=None, direction="to", failed=None): # get type if type is None: type = Node if not issubclass(type, Node): raise ValueError( "{} is not a valid neighbor type," "needs to be a subclass of Node.".format(type) ) # get direction if direction not in ["both", "either", "from", "to"]: raise ValueError( "{} not a valid neighbor connection." "Should be both, either, to or from.".format(direction) ) if failed is not None: raise ValueError( "You should not pass a failed argument to neighbors(). " "Neighbors is " "unusual in that a failed argument cannot be passed. This is " "because there is inherent uncertainty in what it means for a " "neighbor to be failed. The neighbors function will only ever " "return not-failed nodes connected to you via not-failed " "vectors. If you want to do more elaborate queries, for " "example, getting not-failed nodes connected to you via failed" " vectors, you should do so via sql queries." ) neighbors = [] # get the neighbours if direction == "to": outgoing_vectors = ( Vector.query.with_entities(Vector.destination_id) .filter_by(origin_id=self.id, failed=False) .all() ) neighbor_ids = [v.destination_id for v in outgoing_vectors] if neighbor_ids: neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all() neighbors = [n for n in neighbors if isinstance(n, type)] if direction == "from": incoming_vectors = ( Vector.query.with_entities(Vector.origin_id) .filter_by(destination_id=self.id, failed=False) .all() ) neighbor_ids = [v.origin_id for v in incoming_vectors] if neighbor_ids: neighbors = Node.query.filter(Node.id.in_(neighbor_ids)).all() neighbors = [n for n in neighbors if isinstance(n, type)] if direction == "either": neighbors = list( set( self.neighbors(type=type, direction="to") + self.neighbors(type=type, direction="from") ) ) if direction == "both": neighbors = list( set(self.neighbors(type=type, direction="to")) & set(self.neighbors(type=type, direction="from")) ) return neighbors
[ "def", "neighbors", "(", "self", ",", "type", "=", "None", ",", "direction", "=", "\"to\"", ",", "failed", "=", "None", ")", ":", "# get type", "if", "type", "is", "None", ":", "type", "=", "Node", "if", "not", "issubclass", "(", "type", ",", "Node",...
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" (default), "from", "either", or "both".
[ "Get", "a", "node", "s", "neighbors", "-", "nodes", "that", "are", "directly", "connected", "to", "it", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L692-L769
13,222
Dallinger/Dallinger
dallinger/models.py
Node.infos
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(type, Info): raise TypeError( "Cannot get infos of type {} " "as it is not a valid type.".format(type) ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".format(failed)) if failed == "all": return type.query.filter_by(origin_id=self.id).all() else: return type.query.filter_by(origin_id=self.id, failed=failed).all()
python
def infos(self, type=None, failed=False): if type is None: type = Info if not issubclass(type, Info): raise TypeError( "Cannot get infos of type {} " "as it is not a valid type.".format(type) ) if failed not in ["all", False, True]: raise ValueError("{} is not a valid vector failed".format(failed)) if failed == "all": return type.query.filter_by(origin_id=self.id).all() else: return type.query.filter_by(origin_id=self.id, failed=failed).all()
[ "def", "infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "type", "is", "None", ":", "type", "=", "Info", "if", "not", "issubclass", "(", "type", ",", "Info", ")", ":", "raise", "TypeError", "(", "\"Cannot ...
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".
[ "Get", "infos", "that", "originate", "from", "this", "node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L869-L890
13,223
Dallinger/Dallinger
dallinger/models.py
Node.received_infos
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. " "received_infos is " "unusual in that a failed argument cannot be passed. This is " "because there is inherent uncertainty in what it means for a " "received info to be failed. The received_infos function will " "only ever check not-failed transmissions. " "If you want to check failed transmissions " "you should do so via sql queries." ) if type is None: type = Info if not issubclass(type, Info): raise TypeError( "Cannot get infos of type {} " "as it is not a valid type.".format(type) ) transmissions = ( Transmission.query.with_entities(Transmission.info_id) .filter_by(destination_id=self.id, status="received", failed=False) .all() ) info_ids = [t.info_id for t in transmissions] if info_ids: return type.query.filter(type.id.in_(info_ids)).all() else: return []
python
def received_infos(self, type=None, failed=None): if failed is not None: raise ValueError( "You should not pass a failed argument to received_infos. " "received_infos is " "unusual in that a failed argument cannot be passed. This is " "because there is inherent uncertainty in what it means for a " "received info to be failed. The received_infos function will " "only ever check not-failed transmissions. " "If you want to check failed transmissions " "you should do so via sql queries." ) if type is None: type = Info if not issubclass(type, Info): raise TypeError( "Cannot get infos of type {} " "as it is not a valid type.".format(type) ) transmissions = ( Transmission.query.with_entities(Transmission.info_id) .filter_by(destination_id=self.id, status="received", failed=False) .all() ) info_ids = [t.info_id for t in transmissions] if info_ids: return type.query.filter(type.id.in_(info_ids)).all() else: return []
[ "def", "received_infos", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "None", ")", ":", "if", "failed", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You should not pass a failed argument to received_infos. \"", "\"received_infos is \"", "\"...
Get infos that have been sent to this node. Type must be a subclass of info, the default is Info.
[ "Get", "infos", "that", "have", "been", "sent", "to", "this", "node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L892-L927
13,224
Dallinger/Dallinger
dallinger/models.py
Node.transformations
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("{} is not a valid transmission failed".format(failed)) if type is None: type = Transformation if failed == "all": return type.query.filter_by(node_id=self.id).all() else: return type.query.filter_by(node_id=self.id, failed=failed).all()
python
def transformations(self, type=None, failed=False): if failed not in ["all", False, True]: raise ValueError("{} is not a valid transmission failed".format(failed)) if type is None: type = Transformation if failed == "all": return type.query.filter_by(node_id=self.id).all() else: return type.query.filter_by(node_id=self.id, failed=failed).all()
[ "def", "transformations", "(", "self", ",", "type", "=", "None", ",", "failed", "=", "False", ")", ":", "if", "failed", "not", "in", "[", "\"all\"", ",", "False", ",", "True", "]", ":", "raise", "ValueError", "(", "\"{} is not a valid transmission failed\"",...
Get Transformations done by this Node. type must be a type of Transformation (defaults to Transformation) Failed can be True, False or "all"
[ "Get", "Transformations", "done", "by", "this", "Node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1022-L1038
13,225
Dallinger/Dallinger
dallinger/models.py
Node.fail
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_death` to now. Instruct all not-failed vectors connected to this node, infos made by this node, transmissions to or from this node and transformations made by this node to fail. """ if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() self.network.calculate_full() for v in self.vectors(): v.fail() for i in self.infos(): i.fail() for t in self.transmissions(direction="all"): t.fail() for t in self.transformations(): t.fail()
python
def fail(self): if self.failed is True: raise AttributeError("Cannot fail {} - it has already failed.".format(self)) else: self.failed = True self.time_of_death = timenow() self.network.calculate_full() for v in self.vectors(): v.fail() for i in self.infos(): i.fail() for t in self.transmissions(direction="all"): t.fail() for t in self.transformations(): t.fail()
[ "def", "fail", "(", "self", ")", ":", "if", "self", ".", "failed", "is", "True", ":", "raise", "AttributeError", "(", "\"Cannot fail {} - it has already failed.\"", ".", "format", "(", "self", ")", ")", "else", ":", "self", ".", "failed", "=", "True", "sel...
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_death` to now. Instruct all not-failed vectors connected to this node, infos made by this node, transmissions to or from this node and transformations made by this node to fail.
[ "Fail", "a", "node", "setting", "its", "status", "to", "failed", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1044-L1072
13,226
Dallinger/Dallinger
dallinger/models.py
Vector.fail
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
def fail(self): 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()
[ "def", "fail", "(", "self", ")", ":", "if", "self", ".", "failed", "is", "True", ":", "raise", "AttributeError", "(", "\"Cannot fail {} - it has already failed.\"", ".", "format", "(", "self", ")", ")", "else", ":", "self", ".", "failed", "=", "True", "sel...
Fail a vector.
[ "Fail", "a", "vector", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1415-L1424
13,227
Dallinger/Dallinger
dallinger/models.py
Info.json_data
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
def json_data(self): return { "type": self.type, "origin_id": self.origin_id, "network_id": self.network_id, "contents": self.contents, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"type\"", ":", "self", ".", "type", ",", "\"origin_id\"", ":", "self", ".", "origin_id", ",", "\"network_id\"", ":", "self", ".", "network_id", ",", "\"contents\"", ":", "self", ".", "contents", ...
The json representation of an info.
[ "The", "json", "representation", "of", "an", "info", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1477-L1484
13,228
Dallinger/Dallinger
dallinger/models.py
Info.transformations
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 only transformations where the info is the ``info_out`` are returned) or ``all`` (in which case any transformations where the info is the ``info_out`` or the ``info_in`` are returned). The default is ``all`` """ if relationship not in ["all", "parent", "child"]: raise ValueError( "You cannot get transformations of relationship {}".format(relationship) + "Relationship can only be parent, child or all." ) if relationship == "all": return Transformation.query.filter( and_( Transformation.failed == false(), or_( Transformation.info_in == self, Transformation.info_out == self ), ) ).all() if relationship == "parent": return Transformation.query.filter_by( info_in_id=self.id, failed=False ).all() if relationship == "child": return Transformation.query.filter_by( info_out_id=self.id, failed=False ).all()
python
def transformations(self, relationship="all"): if relationship not in ["all", "parent", "child"]: raise ValueError( "You cannot get transformations of relationship {}".format(relationship) + "Relationship can only be parent, child or all." ) if relationship == "all": return Transformation.query.filter( and_( Transformation.failed == false(), or_( Transformation.info_in == self, Transformation.info_out == self ), ) ).all() if relationship == "parent": return Transformation.query.filter_by( info_in_id=self.id, failed=False ).all() if relationship == "child": return Transformation.query.filter_by( info_out_id=self.id, failed=False ).all()
[ "def", "transformations", "(", "self", ",", "relationship", "=", "\"all\"", ")", ":", "if", "relationship", "not", "in", "[", "\"all\"", ",", "\"parent\"", ",", "\"child\"", "]", ":", "raise", "ValueError", "(", "\"You cannot get transformations of relationship {}\"...
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 only transformations where the info is the ``info_out`` are returned) or ``all`` (in which case any transformations where the info is the ``info_out`` or the ``info_in`` are returned). The default is ``all``
[ "Get", "all", "the", "transformations", "of", "this", "info", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1521-L1556
13,229
Dallinger/Dallinger
dallinger/models.py
Transmission.json_data
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, "receive_time": self.receive_time, "status": self.status, }
python
def json_data(self): 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, "receive_time": self.receive_time, "status": self.status, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"vector_id\"", ":", "self", ".", "vector_id", ",", "\"origin_id\"", ":", "self", ".", "origin_id", ",", "\"destination_id\"", ":", "self", ".", "destination_id", ",", "\"info_id\"", ":", "self", "."...
The json representation of a transmissions.
[ "The", "json", "representation", "of", "a", "transmissions", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1663-L1673
13,230
Dallinger/Dallinger
dallinger/models.py
Transformation.json_data
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
def json_data(self): 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, }
[ "def", "json_data", "(", "self", ")", ":", "return", "{", "\"info_in_id\"", ":", "self", ".", "info_in_id", ",", "\"info_out_id\"", ":", "self", ".", "info_out_id", ",", "\"node_id\"", ":", "self", ".", "node_id", ",", "\"network_id\"", ":", "self", ".", "...
The json representation of a transformation.
[ "The", "json", "representation", "of", "a", "transformation", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/models.py#L1756-L1763
13,231
Dallinger/Dallinger
dallinger/utils.py
generate_random_id
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
def generate_random_id(size=6, chars=string.ascii_uppercase + string.digits): return "".join(random.choice(chars) for x in range(size))
[ "def", "generate_random_id", "(", "size", "=", "6", ",", "chars", "=", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", ":", "return", "\"\"", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "x", "in", "range", ...
Generate random id numbers.
[ "Generate", "random", "id", "numbers", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/utils.py#L47-L49
13,232
Dallinger/Dallinger
dallinger/command_line.py
report_idle_after
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() message = { "subject": "Idle Experiment.", "body": idle_template.format( app_id=config.get("id"), minutes_so_far=round(seconds / 60) ), } log("Reporting problem with idle experiment...") get_messenger(config).send(message) signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator
python
def report_idle_after(seconds): def decorator(func): def wrapper(*args, **kwargs): def _handle_timeout(signum, frame): config = get_config() if not config.ready: config.load() message = { "subject": "Idle Experiment.", "body": idle_template.format( app_id=config.get("id"), minutes_so_far=round(seconds / 60) ), } log("Reporting problem with idle experiment...") get_messenger(config).send(message) signal.signal(signal.SIGALRM, _handle_timeout) signal.alarm(seconds) try: result = func(*args, **kwargs) finally: signal.alarm(0) return result return wraps(func)(wrapper) return decorator
[ "def", "report_idle_after", "(", "seconds", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_handle_timeout", "(", "signum", ",", "frame", ")", ":", "config", "=", "g...
Report_idle_after after certain number of seconds.
[ "Report_idle_after", "after", "certain", "number", "of", "seconds", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L104-L132
13,233
Dallinger/Dallinger
dallinger/command_line.py
verify_id
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(app[5:13]) ) return app
python
def verify_id(ctx, param, app): 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(app[5:13]) ) return app
[ "def", "verify_id", "(", "ctx", ",", "param", ",", "app", ")", ":", "if", "app", "is", "None", ":", "raise", "TypeError", "(", "\"Select an experiment using the --app parameter.\"", ")", "elif", "app", "[", "0", ":", "5", "]", "==", "\"dlgr-\"", ":", "rais...
Verify the experiment id.
[ "Verify", "the", "experiment", "id", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L135-L144
13,234
Dallinger/Dallinger
dallinger/command_line.py
verify_package
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), ) ok = all(results) return ok
python
def verify_package(verbose=True): results = ( verify_directory(verbose), verify_experiment_module(verbose), verify_config(verbose), verify_no_conflicts(verbose), ) ok = all(results) return ok
[ "def", "verify_package", "(", "verbose", "=", "True", ")", ":", "results", "=", "(", "verify_directory", "(", "verbose", ")", ",", "verify_experiment_module", "(", "verbose", ")", ",", "verify_config", "(", "verbose", ")", ",", "verify_no_conflicts", "(", "ver...
Perform a series of checks on the current directory to verify that it's a valid Dallinger experiment.
[ "Perform", "a", "series", "of", "checks", "on", "the", "current", "directory", "to", "verify", "that", "it", "s", "a", "valid", "Dallinger", "experiment", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L307-L320
13,235
Dallinger/Dallinger
dallinger/command_line.py
require_exp_directory
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")): raise click.UsageError(error) return f(**kwargs) return wrapper
python
def require_exp_directory(f): error = "The current directory is not a valid Dallinger experiment." @wraps(f) def wrapper(**kwargs): if not verify_directory(kwargs.get("verbose")): raise click.UsageError(error) return f(**kwargs) return wrapper
[ "def", "require_exp_directory", "(", "f", ")", ":", "error", "=", "\"The current directory is not a valid Dallinger experiment.\"", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "*", "kwargs", ")", ":", "if", "not", "verify_directory", "(", "kwargs", ...
Decorator to verify that a command is run inside a valid Dallinger experiment directory.
[ "Decorator", "to", "verify", "that", "a", "command", "is", "run", "inside", "a", "valid", "Dallinger", "experiment", "directory", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L323-L335
13,236
Dallinger/Dallinger
dallinger/command_line.py
dallinger
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
def dallinger(): from logging.config import fileConfig fileConfig( os.path.join(os.path.dirname(__file__), "logging.ini"), disable_existing_loggers=False, )
[ "def", "dallinger", "(", ")", ":", "from", "logging", ".", "config", "import", "fileConfig", "fileConfig", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"logging.ini\"", ")", ",", "disable_exist...
Dallinger command-line utility.
[ "Dallinger", "command", "-", "line", "utility", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L343-L350
13,237
Dallinger/Dallinger
dallinger/command_line.py
qualify
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 = _mturk_service_from_config(sandbox) if by_name: result = mturk.get_qualification_type_by_name(qualification) if result is None: raise click.BadParameter( 'No qualification with name "{}" exists.'.format(qualification) ) qid = result["id"] else: qid = qualification click.echo( "Assigning qualification {} with value {} to {} worker{}...".format( qid, value, len(workers), "s" if len(workers) > 1 else "" ) ) for worker in workers: if mturk.set_qualification_score(qid, worker, int(value), notify=notify): click.echo("{} OK".format(worker)) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo("{} workers with qualification {}:".format(len(results), qid)) for score, count in Counter([r["score"] for r in results]).items(): click.echo("{} with value {}".format(count, score))
python
def qualify(workers, qualification, value, by_name, notify, sandbox): if not (workers and qualification and value): raise click.BadParameter( "Must specify a qualification ID, value/score, and at least one worker ID" ) mturk = _mturk_service_from_config(sandbox) if by_name: result = mturk.get_qualification_type_by_name(qualification) if result is None: raise click.BadParameter( 'No qualification with name "{}" exists.'.format(qualification) ) qid = result["id"] else: qid = qualification click.echo( "Assigning qualification {} with value {} to {} worker{}...".format( qid, value, len(workers), "s" if len(workers) > 1 else "" ) ) for worker in workers: if mturk.set_qualification_score(qid, worker, int(value), notify=notify): click.echo("{} OK".format(worker)) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo("{} workers with qualification {}:".format(len(results), qid)) for score, count in Counter([r["score"] for r in results]).items(): click.echo("{} with value {}".format(count, score))
[ "def", "qualify", "(", "workers", ",", "qualification", ",", "value", ",", "by_name", ",", "notify", ",", "sandbox", ")", ":", "if", "not", "(", "workers", "and", "qualification", "and", "value", ")", ":", "raise", "click", ".", "BadParameter", "(", "\"M...
Assign a qualification to 1 or more workers
[ "Assign", "a", "qualification", "to", "1", "or", "more", "workers" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L468-L501
13,238
Dallinger/Dallinger
dallinger/command_line.py
revoke
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_config(sandbox) if by_name: result = mturk.get_qualification_type_by_name(qualification) if result is None: raise click.BadParameter( 'No qualification with name "{}" exists.'.format(qualification) ) qid = result["id"] else: qid = qualification if not click.confirm( '\n\nYou are about to revoke qualification "{}" ' "for these workers:\n\t{}\n\n" "This will send an email to each of them from Amazon MTurk. " "Continue?".format(qid, "\n\t".join(workers)) ): click.echo("Aborting...") return for worker in workers: if mturk.revoke_qualification(qid, worker, reason): click.echo( 'Revoked qualification "{}" from worker "{}"'.format(qid, worker) ) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo( 'There are now {} workers with qualification "{}"'.format(len(results), qid) )
python
def revoke(workers, qualification, by_name, reason, sandbox): 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_config(sandbox) if by_name: result = mturk.get_qualification_type_by_name(qualification) if result is None: raise click.BadParameter( 'No qualification with name "{}" exists.'.format(qualification) ) qid = result["id"] else: qid = qualification if not click.confirm( '\n\nYou are about to revoke qualification "{}" ' "for these workers:\n\t{}\n\n" "This will send an email to each of them from Amazon MTurk. " "Continue?".format(qid, "\n\t".join(workers)) ): click.echo("Aborting...") return for worker in workers: if mturk.revoke_qualification(qid, worker, reason): click.echo( 'Revoked qualification "{}" from worker "{}"'.format(qid, worker) ) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo( 'There are now {} workers with qualification "{}"'.format(len(results), qid) )
[ "def", "revoke", "(", "workers", ",", "qualification", ",", "by_name", ",", "reason", ",", "sandbox", ")", ":", "if", "not", "(", "workers", "and", "qualification", ")", ":", "raise", "click", ".", "BadParameter", "(", "\"Must specify a qualification ID or name,...
Revoke a qualification from 1 or more workers
[ "Revoke", "a", "qualification", "from", "1", "or", "more", "workers" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L519-L557
13,239
Dallinger/Dallinger
dallinger/command_line.py
hits
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
def hits(app, sandbox): 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) ) )
[ "def", "hits", "(", "app", ",", "sandbox", ")", ":", "hit_list", "=", "list", "(", "_current_hits", "(", "_mturk_service_from_config", "(", "sandbox", ")", ",", "app", ")", ")", "out", "=", "Output", "(", ")", "out", ".", "log", "(", "\"Found {} hits for...
List hits for an experiment id.
[ "List", "hits", "for", "an", "experiment", "id", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L595-L603
13,240
Dallinger/Dallinger
dallinger/command_line.py
expire
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) success.append(hit_id) except MTurkServiceException: failures.append(hit_id) out = Output() if success: out.log("Expired {} hits: {}".format(len(success), ", ".join(success))) if failures: out.log( "Could not expire {} hits: {}".format(len(failures), ", ".join(failures)) ) if not success and not failures: out.log("No hits found for this application.") if not sandbox: out.log( "If this experiment was run in the MTurk sandbox, use: " "`dallinger expire --sandbox --app {}`".format(app) ) if exit and not success: sys.exit(1)
python
def expire(app, sandbox, exit=True): 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) success.append(hit_id) except MTurkServiceException: failures.append(hit_id) out = Output() if success: out.log("Expired {} hits: {}".format(len(success), ", ".join(success))) if failures: out.log( "Could not expire {} hits: {}".format(len(failures), ", ".join(failures)) ) if not success and not failures: out.log("No hits found for this application.") if not sandbox: out.log( "If this experiment was run in the MTurk sandbox, use: " "`dallinger expire --sandbox --app {}`".format(app) ) if exit and not success: sys.exit(1)
[ "def", "expire", "(", "app", ",", "sandbox", ",", "exit", "=", "True", ")", ":", "success", "=", "[", "]", "failures", "=", "[", "]", "service", "=", "_mturk_service_from_config", "(", "sandbox", ")", "hits", "=", "_current_hits", "(", "service", ",", ...
Expire hits for an experiment id.
[ "Expire", "hits", "for", "an", "experiment", "id", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L614-L642
13,241
Dallinger/Dallinger
dallinger/command_line.py
destroy
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
def destroy(ctx, app, expire_hit, sandbox): if expire_hit: ctx.invoke(expire, app=app, sandbox=sandbox, exit=False) HerokuApp(app).destroy()
[ "def", "destroy", "(", "ctx", ",", "app", ",", "expire_hit", ",", "sandbox", ")", ":", "if", "expire_hit", ":", "ctx", ".", "invoke", "(", "expire", ",", "app", "=", "app", ",", "sandbox", "=", "sandbox", ",", "exit", "=", "False", ")", "HerokuApp", ...
Tear down an experiment server.
[ "Tear", "down", "an", "experiment", "server", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L662-L666
13,242
Dallinger/Dallinger
dallinger/command_line.py
monitor
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(): summary = get_summary(app) click.clear() click.echo(header) click.echo("\nExperiment {}\n".format(app)) click.echo(summary) time.sleep(10)
python
def monitor(app): 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(): summary = get_summary(app) click.clear() click.echo(header) click.echo("\nExperiment {}\n".format(app)) click.echo(summary) time.sleep(10)
[ "def", "monitor", "(", "app", ")", ":", "heroku_app", "=", "HerokuApp", "(", "dallinger_uid", "=", "app", ")", "webbrowser", ".", "open", "(", "heroku_app", ".", "dashboard_url", ")", "webbrowser", ".", "open", "(", "\"https://requester.mturk.com/mturk/manageHITs\...
Set up application monitoring.
[ "Set", "up", "application", "monitoring", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L740-L753
13,243
Dallinger/Dallinger
dallinger/command_line.py
bot
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() assignment = generate_random_id() ad_url = "{}/ad".format(heroku_app.url) ad_parameters = "assignmentId={}&hitId={}&workerId={}&mode=sandbox" ad_parameters = ad_parameters.format(assignment, hit, worker) url = "{}?{}".format(ad_url, ad_parameters) bot = bot_factory(url) bot.run_experiment()
python
def bot(app, debug): 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() assignment = generate_random_id() ad_url = "{}/ad".format(heroku_app.url) ad_parameters = "assignmentId={}&hitId={}&workerId={}&mode=sandbox" ad_parameters = ad_parameters.format(assignment, hit, worker) url = "{}?{}".format(ad_url, ad_parameters) bot = bot_factory(url) bot.run_experiment()
[ "def", "bot", "(", "app", ",", "debug", ")", ":", "if", "debug", "is", "None", ":", "verify_id", "(", "None", ",", "None", ",", "app", ")", "(", "id", ",", "tmp", ")", "=", "setup_experiment", "(", "log", ")", "if", "debug", ":", "url", "=", "d...
Run the experiment bot.
[ "Run", "the", "experiment", "bot", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/command_line.py#L773-L792
13,244
Dallinger/Dallinger
demos/dlgr/demos/sheep_market/experiment.py
getdrawings
def getdrawings(): """Get all the drawings.""" infos = Info.query.all() sketches = [json.loads(info.contents) for info in infos] return jsonify(drawings=sketches)
python
def getdrawings(): infos = Info.query.all() sketches = [json.loads(info.contents) for info in infos] return jsonify(drawings=sketches)
[ "def", "getdrawings", "(", ")", ":", "infos", "=", "Info", ".", "query", ".", "all", "(", ")", "sketches", "=", "[", "json", ".", "loads", "(", "info", ".", "contents", ")", "for", "info", "in", "infos", "]", "return", "jsonify", "(", "drawings", "...
Get all the drawings.
[ "Get", "all", "the", "drawings", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/demos/dlgr/demos/sheep_market/experiment.py#L37-L41
13,245
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
inject_experiment
def inject_experiment(): """Inject experiment and enviroment variables into the template context.""" exp = Experiment(session) return dict(experiment=exp, env=os.environ)
python
def inject_experiment(): exp = Experiment(session) return dict(experiment=exp, env=os.environ)
[ "def", "inject_experiment", "(", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "return", "dict", "(", "experiment", "=", "exp", ",", "env", "=", "os", ".", "environ", ")" ]
Inject experiment and enviroment variables into the template context.
[ "Inject", "experiment", "and", "enviroment", "variables", "into", "the", "template", "context", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L309-L312
13,246
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
consent
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=config.get("mode"), )
python
def consent(): 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=config.get("mode"), )
[ "def", "consent", "(", ")", ":", "config", "=", "_config", "(", ")", "return", "render_template", "(", "\"consent.html\"", ",", "hit_id", "=", "request", ".", "args", "[", "\"hit_id\"", "]", ",", "assignment_id", "=", "request", ".", "args", "[", "\"assign...
Return the consent form. Here for backwards-compatibility with 2.x.
[ "Return", "the", "consent", "form", ".", "Here", "for", "backwards", "-", "compatibility", "with", "2", ".", "x", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L731-L740
13,247
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
request_parameter
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 If the parameter is not found and no default is specified, or if the parameter is found but is of the wrong type then a Response object is returned """ exp = Experiment(session) # get the parameter try: value = request.values[parameter] except KeyError: # if it isnt found use the default, or return an error Response if default is not None: return default elif optional: return None else: msg = "{} {} request, {} not specified".format( request.url, request.method, parameter ) return error_response(error_type=msg) # check the parameter type if parameter_type is None: # if no parameter_type is required, return the parameter as is return value elif parameter_type == "int": # if int is required, convert to an int try: value = int(value) return value except ValueError: msg = "{} {} request, non-numeric {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) elif parameter_type == "known_class": # if its a known class check against the known classes try: value = exp.known_classes[value] return value except KeyError: msg = "{} {} request, unknown_class: {} for parameter {}".format( request.url, request.method, value, parameter ) return error_response(error_type=msg) elif parameter_type == "bool": # if its a boolean, convert to a boolean if value in ["True", "False"]: return value == "True" else: msg = "{} {} request, non-boolean {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) else: msg = "/{} {} request, unknown parameter type: {} for parameter {}".format( request.url, request.method, parameter_type, parameter ) return error_response(error_type=msg)
python
def request_parameter(parameter, parameter_type=None, default=None, optional=False): exp = Experiment(session) # get the parameter try: value = request.values[parameter] except KeyError: # if it isnt found use the default, or return an error Response if default is not None: return default elif optional: return None else: msg = "{} {} request, {} not specified".format( request.url, request.method, parameter ) return error_response(error_type=msg) # check the parameter type if parameter_type is None: # if no parameter_type is required, return the parameter as is return value elif parameter_type == "int": # if int is required, convert to an int try: value = int(value) return value except ValueError: msg = "{} {} request, non-numeric {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) elif parameter_type == "known_class": # if its a known class check against the known classes try: value = exp.known_classes[value] return value except KeyError: msg = "{} {} request, unknown_class: {} for parameter {}".format( request.url, request.method, value, parameter ) return error_response(error_type=msg) elif parameter_type == "bool": # if its a boolean, convert to a boolean if value in ["True", "False"]: return value == "True" else: msg = "{} {} request, non-boolean {}: {}".format( request.url, request.method, parameter, value ) return error_response(error_type=msg) else: msg = "/{} {} request, unknown parameter type: {} for parameter {}".format( request.url, request.method, parameter_type, parameter ) return error_response(error_type=msg)
[ "def", "request_parameter", "(", "parameter", ",", "parameter_type", "=", "None", ",", "default", "=", "None", ",", "optional", "=", "False", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "# get the parameter", "try", ":", "value", "=", "request",...
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 If the parameter is not found and no default is specified, or if the parameter is found but is of the wrong type then a Response object is returned
[ "Get", "a", "parameter", "from", "a", "request", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L746-L811
13,248
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
node_vectors
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])
python
def node_vectors(node_id): 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])
[ "def", "node_vectors", "(", "node_id", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "# get the parameters", "direction", "=", "request_parameter", "(", "parameter", "=", "\"direction\"", ",", "default", "=", "\"all\"", ")", "failed", "=", "request_pa...
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).
[ "Get", "the", "vectors", "of", "a", "node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1109-L1141
13,249
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
node_received_infos
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_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])
python
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])
[ "def", "node_received_infos", "(", "node_id", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "# get the parameters", "info_type", "=", "request_parameter", "(", "parameter", "=", "\"info_type\"", ",", "parameter_type", "=", "\"known_class\"", ",", "default...
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.
[ "Get", "all", "the", "infos", "a", "node", "has", "been", "sent", "and", "has", "received", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1273-L1310
13,250
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
tracking_event_post
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: return error_response(error_type="/info POST, node does not exist") db.logger.debug( "rq: Queueing %s with for node: %s for worker_function", "TrackingEvent", node_id, ) q.enqueue( worker_function, "TrackingEvent", None, None, node_id=node_id, details=details ) return success_response(details=details)
python
def tracking_event_post(node_id): 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: return error_response(error_type="/info POST, node does not exist") db.logger.debug( "rq: Queueing %s with for node: %s for worker_function", "TrackingEvent", node_id, ) q.enqueue( worker_function, "TrackingEvent", None, None, node_id=node_id, details=details ) return success_response(details=details)
[ "def", "tracking_event_post", "(", "node_id", ")", ":", "details", "=", "request_parameter", "(", "parameter", "=", "\"details\"", ",", "optional", "=", "True", ")", "if", "details", ":", "details", "=", "loads", "(", "details", ")", "# check the node exists", ...
Enqueue a TrackingEvent worker for the specified Node.
[ "Enqueue", "a", "TrackingEvent", "worker", "for", "the", "specified", "Node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1315-L1336
13,251
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
info_post
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__())
python
def info_post(node_id): # 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__())
[ "def", "info_post", "(", "node_id", ")", ":", "# get the parameters and validate them", "contents", "=", "request_parameter", "(", "parameter", "=", "\"contents\"", ")", "info_type", "=", "request_parameter", "(", "parameter", "=", "\"info_type\"", ",", "parameter_type"...
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.
[ "Create", "an", "info", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1341-L1382
13,252
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
node_transmissions
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])
python
def node_transmissions(node_id): 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])
[ "def", "node_transmissions", "(", "node_id", ")", ":", "exp", "=", "Experiment", "(", "session", ")", "# get the parameters", "direction", "=", "request_parameter", "(", "parameter", "=", "\"direction\"", ",", "default", "=", "\"incoming\"", ")", "status", "=", ...
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.
[ "Get", "all", "the", "transmissions", "of", "a", "node", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1386-L1425
13,253
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
check_for_duplicate_assignments
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)
python
def check_for_duplicate_assignments(participant): 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)
[ "def", "check_for_duplicate_assignments", "(", "participant", ")", ":", "participants", "=", "models", ".", "Participant", ".", "query", ".", "filter_by", "(", "assignment_id", "=", "participant", ".", "assignment_id", ")", ".", "all", "(", ")", "duplicates", "=...
Check that the assignment_id of the participant is unique. If it isnt the older participants will be failed.
[ "Check", "that", "the", "assignment_id", "of", "the", "participant", "is", "unique", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1649-L1661
13,254
Dallinger/Dallinger
dallinger/experiment_server/experiment_server.py
worker_failed
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(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" )
python
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" )
[ "def", "worker_failed", "(", ")", ":", "participant_id", "=", "request", ".", "args", ".", "get", "(", "\"participant_id\"", ")", "if", "not", "participant_id", ":", "return", "error_response", "(", "error_type", "=", "\"bad request\"", ",", "error_text", "=", ...
Fail worker. Used by bots only for now.
[ "Fail", "worker", ".", "Used", "by", "bots", "only", "for", "now", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment_server/experiment_server.py#L1712-L1729
13,255
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuInfo.all_apps
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
def all_apps(self): cmd = ["heroku", "apps", "--json"] if self.team: cmd.extend(["--team", self.team]) return json.loads(self._result(cmd))
[ "def", "all_apps", "(", "self", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "\"apps\"", ",", "\"--json\"", "]", "if", "self", ".", "team", ":", "cmd", ".", "extend", "(", "[", "\"--team\"", ",", "self", ".", "team", "]", ")", "return", "json", "....
Capture a backup of the app.
[ "Capture", "a", "backup", "of", "the", "app", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L61-L66
13,256
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.bootstrap
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 )
python
def bootstrap(self): 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 )
[ "def", "bootstrap", "(", "self", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "\"apps:create\"", ",", "self", ".", "name", ",", "\"--buildpack\"", ",", "\"heroku/python\"", "]", "# If a team is specified, assign the app to the team.", "if", "self", ".", "team", "...
Creates the heroku app and local git remote. Call this once you're in the local repo you're going to use.
[ "Creates", "the", "heroku", "app", "and", "local", "git", "remote", ".", "Call", "this", "once", "you", "re", "in", "the", "local", "repo", "you", "re", "going", "to", "use", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L92-L106
13,257
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.addon
def addon(self, name): """Set up an addon""" cmd = ["heroku", "addons:create", name, "--app", self.name] self._run(cmd)
python
def addon(self, name): cmd = ["heroku", "addons:create", name, "--app", self.name] self._run(cmd)
[ "def", "addon", "(", "self", ",", "name", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "\"addons:create\"", ",", "name", ",", "\"--app\"", ",", "self", ".", "name", "]", "self", ".", "_run", "(", "cmd", ")" ]
Set up an addon
[ "Set", "up", "an", "addon" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L116-L119
13,258
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.addon_destroy
def addon_destroy(self, name): """Destroy an addon""" self._run( [ "heroku", "addons:destroy", name, "--app", self.name, "--confirm", self.name, ] )
python
def addon_destroy(self, name): self._run( [ "heroku", "addons:destroy", name, "--app", self.name, "--confirm", self.name, ] )
[ "def", "addon_destroy", "(", "self", ",", "name", ")", ":", "self", ".", "_run", "(", "[", "\"heroku\"", ",", "\"addons:destroy\"", ",", "name", ",", "\"--app\"", ",", "self", ".", "name", ",", "\"--confirm\"", ",", "self", ".", "name", ",", "]", ")" ]
Destroy an addon
[ "Destroy", "an", "addon" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L121-L133
13,259
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.buildpack
def buildpack(self, url): """Add a buildpack by URL.""" cmd = ["heroku", "buildpacks:add", url, "--app", self.name] self._run(cmd)
python
def buildpack(self, url): cmd = ["heroku", "buildpacks:add", url, "--app", self.name] self._run(cmd)
[ "def", "buildpack", "(", "self", ",", "url", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "\"buildpacks:add\"", ",", "url", ",", "\"--app\"", ",", "self", ".", "name", "]", "self", ".", "_run", "(", "cmd", ")" ]
Add a buildpack by URL.
[ "Add", "a", "buildpack", "by", "URL", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L135-L138
13,260
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.destroy
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
def destroy(self): result = self._result( ["heroku", "apps:destroy", "--app", self.name, "--confirm", self.name] ) return result
[ "def", "destroy", "(", "self", ")", ":", "result", "=", "self", ".", "_result", "(", "[", "\"heroku\"", ",", "\"apps:destroy\"", ",", "\"--app\"", ",", "self", ".", "name", ",", "\"--confirm\"", ",", "self", ".", "name", "]", ")", "return", "result" ]
Destroy an app and all its add-ons
[ "Destroy", "an", "app", "and", "all", "its", "add", "-", "ons" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L190-L195
13,261
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.get
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
def get(self, key, subcommand="config:get"): cmd = ["heroku", subcommand, key, "--app", self.name] return self._result(cmd)
[ "def", "get", "(", "self", ",", "key", ",", "subcommand", "=", "\"config:get\"", ")", ":", "cmd", "=", "[", "\"heroku\"", ",", "subcommand", ",", "key", ",", "\"--app\"", ",", "self", ".", "name", "]", "return", "self", ".", "_result", "(", "cmd", ")...
Get a app config value by name
[ "Get", "a", "app", "config", "value", "by", "name" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L197-L200
13,262
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.pg_wait
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) if not retries: raise else: break
python
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
[ "def", "pg_wait", "(", "self", ")", ":", "retries", "=", "10", "while", "retries", ":", "retries", "=", "retries", "-", "1", "try", ":", "self", ".", "_run", "(", "[", "\"heroku\"", ",", "\"pg:wait\"", ",", "\"--app\"", ",", "self", ".", "name", "]",...
Wait for the DB to be fired up.
[ "Wait", "for", "the", "DB", "to", "be", "fired", "up", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L213-L225
13,263
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.restore
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, "--confirm", self.name, ] )
python
def restore(self, url): self._run( [ "heroku", "pg:backups:restore", "{}".format(url), "DATABASE_URL", "--app", self.name, "--confirm", self.name, ] )
[ "def", "restore", "(", "self", ",", "url", ")", ":", "self", ".", "_run", "(", "[", "\"heroku\"", ",", "\"pg:backups:restore\"", ",", "\"{}\"", ".", "format", "(", "url", ")", ",", "\"DATABASE_URL\"", ",", "\"--app\"", ",", "self", ".", "name", ",", "\...
Restore the remote database from the URL of a backup.
[ "Restore", "the", "remote", "database", "from", "the", "URL", "of", "a", "backup", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L231-L244
13,264
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.scale_up_dyno
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
def scale_up_dyno(self, process, quantity, size): self._run( [ "heroku", "ps:scale", "{}={}:{}".format(process, quantity, size), "--app", self.name, ] )
[ "def", "scale_up_dyno", "(", "self", ",", "process", ",", "quantity", ",", "size", ")", ":", "self", ".", "_run", "(", "[", "\"heroku\"", ",", "\"ps:scale\"", ",", "\"{}={}:{}\"", ".", "format", "(", "process", ",", "quantity", ",", "size", ")", ",", "...
Scale up a dyno.
[ "Scale", "up", "a", "dyno", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L246-L256
13,265
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuApp.scale_down_dynos
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)
python
def scale_down_dynos(self): processes = ["web", "worker"] if self.clock_is_on: processes.append("clock") for process in processes: self.scale_down_dyno(process)
[ "def", "scale_down_dynos", "(", "self", ")", ":", "processes", "=", "[", "\"web\"", ",", "\"worker\"", "]", "if", "self", ".", "clock_is_on", ":", "processes", ".", "append", "(", "\"clock\"", ")", "for", "process", "in", "processes", ":", "self", ".", "...
Turn off web and worker dynos, plus clock process if there is one and it's active.
[ "Turn", "off", "web", "and", "worker", "dynos", "plus", "clock", "process", "if", "there", "is", "one", "and", "it", "s", "active", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L262-L270
13,266
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuLocalWrapper.start
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 raised. """ 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
python
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
[ "def", "start", "(", "self", ",", "timeout_secs", "=", "60", ")", ":", "def", "_handle_timeout", "(", "signum", ",", "frame", ")", ":", "raise", "HerokuTimeoutError", "(", "\"Failed to start after {} seconds.\"", ".", "format", "(", "timeout_secs", ",", "self", ...
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 raised.
[ "Start", "the", "heroku", "local", "subprocess", "group", "and", "verify", "that", "it", "has", "started", "successfully", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L375-L406
13,267
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuLocalWrapper.stop
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
python
def stop(self, signal=None): 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
[ "def", "stop", "(", "self", ",", "signal", "=", "None", ")", ":", "signal", "=", "signal", "or", "self", ".", "int_signal", "self", ".", "out", ".", "log", "(", "\"Cleaning up local Heroku process...\"", ")", "if", "self", ".", "_process", "is", "None", ...
Stop the heroku local subprocess and all of its children.
[ "Stop", "the", "heroku", "local", "subprocess", "and", "all", "of", "its", "children", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L412-L428
13,268
Dallinger/Dallinger
dallinger/heroku/tools.py
HerokuLocalWrapper.monitor
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
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
[ "def", "monitor", "(", "self", ",", "listener", ")", ":", "for", "line", "in", "self", ".", "_stream", "(", ")", ":", "self", ".", "_record", ".", "append", "(", "line", ")", "if", "self", ".", "verbose", ":", "self", ".", "out", ".", "blather", ...
Relay the stream to listener until told to stop.
[ "Relay", "the", "stream", "to", "listener", "until", "told", "to", "stop", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/tools.py#L430-L438
13,269
Dallinger/Dallinger
dallinger/experiment.py
load
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(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
python
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
[ "def", "load", "(", ")", ":", "initialize_experiment_package", "(", "os", ".", "getcwd", "(", ")", ")", "try", ":", "try", ":", "from", "dallinger_experiment", "import", "experiment", "except", "ImportError", ":", "from", "dallinger_experiment", "import", "dalli...
Load the active experiment.
[ "Load", "the", "active", "experiment", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L939-L956
13,270
Dallinger/Dallinger
dallinger/experiment.py
Experiment.setup
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()
python
def setup(self): 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()
[ "def", "setup", "(", "self", ")", ":", "if", "not", "self", ".", "networks", "(", ")", ":", "for", "_", "in", "range", "(", "self", ".", "practice_repeats", ")", ":", "network", "=", "self", ".", "create_network", "(", ")", "network", ".", "role", ...
Create the networks if they don't already exist.
[ "Create", "the", "networks", "if", "they", "don", "t", "already", "exist", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L191-L202
13,271
Dallinger/Dallinger
dallinger/experiment.py
Experiment.networks
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": 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()
python
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()
[ "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 {}\""...
All the networks in the experiment.
[ "All", "the", "networks", "in", "the", "experiment", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L208-L226
13,272
Dallinger/Dallinger
dallinger/experiment.py
Experiment.get_network_for_participant
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 all other networks in a random order. """ 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
python
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
[ "def", "get_network_for_participant", "(", "self", ",", "participant", ")", ":", "key", "=", "participant", ".", "id", "networks_with_space", "=", "(", "Network", ".", "query", ".", "filter_by", "(", "full", "=", "False", ")", ".", "order_by", "(", "Network"...
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 all other networks in a random order.
[ "Find", "a", "network", "for", "a", "participant", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L228-L284
13,273
Dallinger/Dallinger
dallinger/experiment.py
Experiment.recruit
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 all networks are full. """ if not self.networks(full=False): self.log("All networks full: closing recruitment", "-----") self.recruiter.close_recruitment()
python
def recruit(self): if not self.networks(full=False): self.log("All networks full: closing recruitment", "-----") self.recruiter.close_recruitment()
[ "def", "recruit", "(", "self", ")", ":", "if", "not", "self", ".", "networks", "(", "full", "=", "False", ")", ":", "self", ".", "log", "(", "\"All networks full: closing recruitment\"", ",", "\"-----\"", ")", "self", ".", "recruiter", ".", "close_recruitmen...
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 all networks are full.
[ "Recruit", "participants", "to", "the", "experiment", "as", "needed", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L348-L359
13,274
Dallinger/Dallinger
dallinger/experiment.py
Experiment.log_summary
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 summary: {}".format(str(sorted_counts))) return sorted_counts
python
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
[ "def", "log_summary", "(", "self", ")", ":", "participants", "=", "Participant", ".", "query", ".", "with_entities", "(", "Participant", ".", "status", ")", ".", "all", "(", ")", "counts", "=", "Counter", "(", "[", "p", ".", "status", "for", "p", "in",...
Log a summary of all the participants' status codes.
[ "Log", "a", "summary", "of", "all", "the", "participants", "status", "codes", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L367-L373
13,275
Dallinger/Dallinger
dallinger/experiment.py
Experiment.save
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
def save(self, *objects): if len(objects) > 0: self.session.add_all(objects) self.session.commit()
[ "def", "save", "(", "self", ",", "*", "objects", ")", ":", "if", "len", "(", "objects", ")", ">", "0", ":", "self", ".", "session", ".", "add_all", "(", "objects", ")", "self", ".", "session", ".", "commit", "(", ")" ]
Add all the objects to the session and commit them. This only needs to be done for networks and participants.
[ "Add", "all", "the", "objects", "to", "the", "session", "and", "commit", "them", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L375-L383
13,276
Dallinger/Dallinger
dallinger/experiment.py
Experiment.fail_participant
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
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()
[ "def", "fail_participant", "(", "self", ",", "participant", ")", ":", "participant_nodes", "=", "Node", ".", "query", ".", "filter_by", "(", "participant_id", "=", "participant", ".", "id", ",", "failed", "=", "False", ")", ".", "all", "(", ")", "for", "...
Fail all the nodes of a participant.
[ "Fail", "all", "the", "nodes", "of", "a", "participant", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L425-L432
13,277
Dallinger/Dallinger
dallinger/experiment.py
Experiment.run
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
python
def run(self, exp_config=None, app_id=None, bot=False, **kwargs): 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
[ "def", "run", "(", "self", ",", "exp_config", "=", "None", ",", "app_id", "=", "None", ",", "bot", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "dallinger", "as", "dlgr", "app_id", "=", "self", ".", "make_uuid", "(", "app_id", ")", "i...
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.
[ "Deploy", "and", "run", "an", "experiment", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L487-L525
13,278
Dallinger/Dallinger
dallinger/experiment.py
Experiment.collect
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)
python
def collect(self, app_id, exp_config=None, bot=False, **kwargs): 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)
[ "def", "collect", "(", "self", ",", "app_id", ",", "exp_config", "=", "None", ",", "bot", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "results", "=", "data_load", "(", "app_id", ")", "self", ".", "log", "(", "\"Data found for experimen...
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.
[ "Collect", "data", "for", "the", "provided", "experiment", "id", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L527-L568
13,279
Dallinger/Dallinger
dallinger/experiment.py
Experiment.retrieve_data
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(filename)
python
def retrieve_data(self): 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(filename)
[ "def", "retrieve_data", "(", "self", ")", ":", "local", "=", "False", "if", "self", ".", "exp_config", ".", "get", "(", "\"mode\"", ")", "==", "\"debug\"", ":", "local", "=", "True", "filename", "=", "export", "(", "self", ".", "app_id", ",", "local", ...
Retrieves and saves data from a running experiment
[ "Retrieves", "and", "saves", "data", "from", "a", "running", "experiment" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L609-L616
13,280
Dallinger/Dallinger
dallinger/experiment.py
Experiment.end_experiment
def end_experiment(self): """Terminates a running experiment""" if self.exp_config.get("mode") != "debug": HerokuApp(self.app_id).destroy() return True
python
def end_experiment(self): if self.exp_config.get("mode") != "debug": HerokuApp(self.app_id).destroy() return True
[ "def", "end_experiment", "(", "self", ")", ":", "if", "self", ".", "exp_config", ".", "get", "(", "\"mode\"", ")", "!=", "\"debug\"", ":", "HerokuApp", "(", "self", ".", "app_id", ")", ".", "destroy", "(", ")", "return", "True" ]
Terminates a running experiment
[ "Terminates", "a", "running", "experiment" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L618-L622
13,281
Dallinger/Dallinger
dallinger/experiment.py
Scrubber._ipython_display_
def _ipython_display_(self): """Display Jupyter Notebook widget""" from IPython.display import display self.build_widget() display(self.widget())
python
def _ipython_display_(self): from IPython.display import display self.build_widget() display(self.widget())
[ "def", "_ipython_display_", "(", "self", ")", ":", "from", "IPython", ".", "display", "import", "display", "self", ".", "build_widget", "(", ")", "display", "(", "self", ".", "widget", "(", ")", ")" ]
Display Jupyter Notebook widget
[ "Display", "Jupyter", "Notebook", "widget" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/experiment.py#L931-L936
13,282
Dallinger/Dallinger
dallinger/recruiters.py
from_config
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 = config.get("recruiter", None) recruiter = None # Special case 1: Don't use a configured recruiter in replay mode if config.get("replay"): return HotAirRecruiter() if name is not None: recruiter = by_name(name) # Special case 2: may run BotRecruiter or MultiRecruiter in any mode # (debug or not), so it trumps everything else: if isinstance(recruiter, (BotRecruiter, MultiRecruiter)): return recruiter # Special case 3: if we're not using bots and we're in debug mode, # ignore any configured recruiter: if debug_mode: return HotAirRecruiter() # Configured recruiter: if recruiter is not None: return recruiter if name and recruiter is None: raise NotImplementedError("No such recruiter {}".format(name)) # Default if we're not in debug mode: return MTurkRecruiter()
python
def from_config(config): debug_mode = config.get("mode") == "debug" name = config.get("recruiter", None) recruiter = None # Special case 1: Don't use a configured recruiter in replay mode if config.get("replay"): return HotAirRecruiter() if name is not None: recruiter = by_name(name) # Special case 2: may run BotRecruiter or MultiRecruiter in any mode # (debug or not), so it trumps everything else: if isinstance(recruiter, (BotRecruiter, MultiRecruiter)): return recruiter # Special case 3: if we're not using bots and we're in debug mode, # ignore any configured recruiter: if debug_mode: return HotAirRecruiter() # Configured recruiter: if recruiter is not None: return recruiter if name and recruiter is None: raise NotImplementedError("No such recruiter {}".format(name)) # Default if we're not in debug mode: return MTurkRecruiter()
[ "def", "from_config", "(", "config", ")", ":", "debug_mode", "=", "config", ".", "get", "(", "\"mode\"", ")", "==", "\"debug\"", "name", "=", "config", ".", "get", "(", "\"recruiter\"", ",", "None", ")", "recruiter", "=", "None", "# Special case 1: Don't use...
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.
[ "Return", "a", "Recruiter", "instance", "based", "on", "the", "configuration", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L936-L972
13,283
Dallinger/Dallinger
dallinger/recruiters.py
CLIRecruiter.recruit
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.format( get_base_url(), self.nickname, generate_random_id(), generate_random_id(), generate_random_id(), self._get_mode(), ) logger.info("{} {}".format(NEW_RECRUIT_LOG_PREFIX, ad_url)) urls.append(ad_url) return urls
python
def recruit(self, n=1): logger.info("Recruiting {} CLI participants".format(n)) urls = [] template = "{}/ad?recruiter={}&assignmentId={}&hitId={}&workerId={}&mode={}" for i in range(n): ad_url = template.format( get_base_url(), self.nickname, generate_random_id(), generate_random_id(), generate_random_id(), self._get_mode(), ) logger.info("{} {}".format(NEW_RECRUIT_LOG_PREFIX, ad_url)) urls.append(ad_url) return urls
[ "def", "recruit", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Recruiting {} CLI participants\"", ".", "format", "(", "n", ")", ")", "urls", "=", "[", "]", "template", "=", "\"{}/ad?recruiter={}&assignmentId={}&hitId={}&workerId={}&m...
Generate experiemnt URLs and print them to the console.
[ "Generate", "experiemnt", "URLs", "and", "print", "them", "to", "the", "console", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L143-L160
13,284
Dallinger/Dallinger
dallinger/recruiters.py
CLIRecruiter.reward_bonus
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
def reward_bonus(self, assignment_id, amount, reason): logger.info( 'Award ${} for assignment {}, with reason "{}"'.format( amount, assignment_id, reason ) )
[ "def", "reward_bonus", "(", "self", ",", "assignment_id", ",", "amount", ",", "reason", ")", ":", "logger", ".", "info", "(", "'Award ${} for assignment {}, with reason \"{}\"'", ".", "format", "(", "amount", ",", "assignment_id", ",", "reason", ")", ")" ]
Print out bonus info for the assignment
[ "Print", "out", "bonus", "info", "for", "the", "assignment" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L171-L177
13,285
Dallinger/Dallinger
dallinger/recruiters.py
SimulatedRecruiter.open_recruitment
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
def open_recruitment(self, n=1): logger.info("Opening Sim recruitment for {} participants".format(n)) return {"items": self.recruit(n), "message": "Simulated recruitment only"}
[ "def", "open_recruitment", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Opening Sim recruitment for {} participants\"", ".", "format", "(", "n", ")", ")", "return", "{", "\"items\"", ":", "self", ".", "recruit", "(", "n", ")", ...
Open recruitment.
[ "Open", "recruitment", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L219-L222
13,286
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter.open_recruitment
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." ) if self.hit_domain is None: raise MTurkRecruiterException("Can't run a HIT from localhost") self.mturkservice.check_credentials() if self.config.get("assign_qualifications"): self._create_mturk_qualifications() hit_request = { "max_assignments": n, "title": self.config.get("title"), "description": self.config.get("description"), "keywords": self._config_to_list("keywords"), "reward": self.config.get("base_payment"), "duration_hours": self.config.get("duration"), "lifetime_days": self.config.get("lifetime"), "ad_url": self.ad_url, "notification_url": self.config.get("notification_url"), "approve_requirement": self.config.get("approve_requirement"), "us_only": self.config.get("us_only"), "blacklist": self._config_to_list("qualification_blacklist"), "annotation": self.config.get("id"), } hit_info = self.mturkservice.create_hit(**hit_request) if self.config.get("mode") == "sandbox": lookup_url = ( "https://workersandbox.mturk.com/mturk/preview?groupId={type_id}" ) else: lookup_url = "https://worker.mturk.com/mturk/preview?groupId={type_id}" return { "items": [lookup_url.format(**hit_info)], "message": "HIT now published to Amazon Mechanical Turk", }
python
def open_recruitment(self, n=1): logger.info("Opening MTurk recruitment for {} participants".format(n)) if self.is_in_progress: raise MTurkRecruiterException( "Tried to open_recruitment on already open recruiter." ) if self.hit_domain is None: raise MTurkRecruiterException("Can't run a HIT from localhost") self.mturkservice.check_credentials() if self.config.get("assign_qualifications"): self._create_mturk_qualifications() hit_request = { "max_assignments": n, "title": self.config.get("title"), "description": self.config.get("description"), "keywords": self._config_to_list("keywords"), "reward": self.config.get("base_payment"), "duration_hours": self.config.get("duration"), "lifetime_days": self.config.get("lifetime"), "ad_url": self.ad_url, "notification_url": self.config.get("notification_url"), "approve_requirement": self.config.get("approve_requirement"), "us_only": self.config.get("us_only"), "blacklist": self._config_to_list("qualification_blacklist"), "annotation": self.config.get("id"), } hit_info = self.mturkservice.create_hit(**hit_request) if self.config.get("mode") == "sandbox": lookup_url = ( "https://workersandbox.mturk.com/mturk/preview?groupId={type_id}" ) else: lookup_url = "https://worker.mturk.com/mturk/preview?groupId={type_id}" return { "items": [lookup_url.format(**hit_info)], "message": "HIT now published to Amazon Mechanical Turk", }
[ "def", "open_recruitment", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Opening MTurk recruitment for {} participants\"", ".", "format", "(", "n", ")", ")", "if", "self", ".", "is_in_progress", ":", "raise", "MTurkRecruiterException"...
Open a connection to AWS MTurk and create a HIT.
[ "Open", "a", "connection", "to", "AWS", "MTurk", "and", "create", "a", "HIT", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L440-L482
13,287
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter.recruit
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_hit_id() if hit_id is None: logger.info("no HIT in progress: recruitment aborted") return try: return self.mturkservice.extend_hit( hit_id, number=n, duration_hours=self.config.get("duration") ) except MTurkServiceException as ex: logger.exception(str(ex))
python
def recruit(self, n=1): 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_hit_id() if hit_id is None: logger.info("no HIT in progress: recruitment aborted") return try: return self.mturkservice.extend_hit( hit_id, number=n, duration_hours=self.config.get("duration") ) except MTurkServiceException as ex: logger.exception(str(ex))
[ "def", "recruit", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Recruiting {} MTurk participants\"", ".", "format", "(", "n", ")", ")", "if", "not", "self", ".", "config", ".", "get", "(", "\"auto_recruit\"", ")", ":", "logg...
Recruit n new participants to an existing HIT
[ "Recruit", "n", "new", "participants", "to", "an", "existing", "HIT" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L484-L501
13,288
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter.notify_completed
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 them to remain eligible for future runs. """ if participant.status == "overrecruited" or not self.qualification_active: return worker_id = participant.worker_id for name in self.qualifications: try: self.mturkservice.increment_qualification_score(name, worker_id) except QualificationNotFoundException as ex: logger.exception(ex)
python
def notify_completed(self, participant): if participant.status == "overrecruited" or not self.qualification_active: return worker_id = participant.worker_id for name in self.qualifications: try: self.mturkservice.increment_qualification_score(name, worker_id) except QualificationNotFoundException as ex: logger.exception(ex)
[ "def", "notify_completed", "(", "self", ",", "participant", ")", ":", "if", "participant", ".", "status", "==", "\"overrecruited\"", "or", "not", "self", ".", "qualification_active", ":", "return", "worker_id", "=", "participant", ".", "worker_id", "for", "name"...
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 them to remain eligible for future runs.
[ "Assign", "a", "Qualification", "to", "the", "Participant", "for", "the", "experiment", "ID", "and", "for", "the", "configured", "group_name", "if", "it", "s", "been", "set", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L503-L520
13,289
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter.notify_duration_exceeded
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 participant in participants: summary = ParticipationTime(participant, reference_time, self.config) status = self._mturk_status_for(participant) if status == "Approved": participant.status = "approved" session.commit() elif status == "Rejected": participant.status = "rejected" session.commit() elif status == "Submitted": self._resend_submitted_rest_notification_for(participant) self._message_researcher(self._resubmitted_msg(summary)) logger.warning( "Error - submitted notification for participant {} missed. " "A replacement notification was created and sent, " "but proceed with caution.".format(participant.id) ) else: self._send_notification_missing_rest_notification_for(participant) unsubmitted.append(summary) if unsubmitted: self._disable_autorecruit() self.close_recruitment() pick_one = unsubmitted[0] # message the researcher about the one of the participants: self._message_researcher(self._cancelled_msg(pick_one)) # Attempt to force-expire the hit via boto. It's possible # that the HIT won't exist if the HIT has been deleted manually. try: self.mturkservice.expire_hit(pick_one.participant.hit_id) except MTurkServiceException as ex: logger.exception(ex)
python
def notify_duration_exceeded(self, participants, reference_time): unsubmitted = [] for participant in participants: summary = ParticipationTime(participant, reference_time, self.config) status = self._mturk_status_for(participant) if status == "Approved": participant.status = "approved" session.commit() elif status == "Rejected": participant.status = "rejected" session.commit() elif status == "Submitted": self._resend_submitted_rest_notification_for(participant) self._message_researcher(self._resubmitted_msg(summary)) logger.warning( "Error - submitted notification for participant {} missed. " "A replacement notification was created and sent, " "but proceed with caution.".format(participant.id) ) else: self._send_notification_missing_rest_notification_for(participant) unsubmitted.append(summary) if unsubmitted: self._disable_autorecruit() self.close_recruitment() pick_one = unsubmitted[0] # message the researcher about the one of the participants: self._message_researcher(self._cancelled_msg(pick_one)) # Attempt to force-expire the hit via boto. It's possible # that the HIT won't exist if the HIT has been deleted manually. try: self.mturkservice.expire_hit(pick_one.participant.hit_id) except MTurkServiceException as ex: logger.exception(ex)
[ "def", "notify_duration_exceeded", "(", "self", ",", "participants", ",", "reference_time", ")", ":", "unsubmitted", "=", "[", "]", "for", "participant", "in", "participants", ":", "summary", "=", "ParticipationTime", "(", "participant", ",", "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.
[ "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", "...
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L522-L561
13,290
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter.reward_bonus
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
def reward_bonus(self, assignment_id, amount, reason): try: return self.mturkservice.grant_bonus(assignment_id, amount, reason) except MTurkServiceException as ex: logger.exception(str(ex))
[ "def", "reward_bonus", "(", "self", ",", "assignment_id", ",", "amount", ",", "reason", ")", ":", "try", ":", "return", "self", ".", "mturkservice", ".", "grant_bonus", "(", "assignment_id", ",", "amount", ",", "reason", ")", "except", "MTurkServiceException",...
Reward the Turker for a specified assignment with a bonus.
[ "Reward", "the", "Turker", "for", "a", "specified", "assignment", "with", "a", "bonus", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L583-L588
13,291
Dallinger/Dallinger
dallinger/recruiters.py
MTurkRecruiter._create_mturk_qualifications
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(): try: self.mturkservice.create_qualification_type(name, desc) except DuplicateQualificationNameError: pass
python
def _create_mturk_qualifications(self): for name, desc in self.qualifications.items(): try: self.mturkservice.create_qualification_type(name, desc) except DuplicateQualificationNameError: pass
[ "def", "_create_mturk_qualifications", "(", "self", ")", ":", "for", "name", ",", "desc", "in", "self", ".", "qualifications", ".", "items", "(", ")", ":", "try", ":", "self", ".", "mturkservice", ".", "create_qualification_type", "(", "name", ",", "desc", ...
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.
[ "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", ...
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L670-L679
13,292
Dallinger/Dallinger
dallinger/recruiters.py
BotRecruiter.open_recruitment
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), "message": "Bot recruitment started using {}".format(bot_class_name), }
python
def open_recruitment(self, n=1): 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), "message": "Bot recruitment started using {}".format(bot_class_name), }
[ "def", "open_recruitment", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Opening Bot recruitment for {} participants\"", ".", "format", "(", "n", ")", ")", "factory", "=", "self", ".", "_get_bot_factory", "(", ")", "bot_class_name",...
Start recruiting right away.
[ "Start", "recruiting", "right", "away", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L756-L764
13,293
Dallinger/Dallinger
dallinger/recruiters.py
BotRecruiter.recruit
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 = generate_random_id() hit = generate_random_id() assignment = generate_random_id() ad_parameters = ( "recruiter={}&assignmentId={}&hitId={}&workerId={}&mode=sandbox" ) ad_parameters = ad_parameters.format(self.nickname, assignment, hit, worker) url = "{}/ad?{}".format(base_url, ad_parameters) urls.append(url) bot = factory(url, assignment_id=assignment, worker_id=worker, hit_id=hit) job = q.enqueue(bot.run_experiment, timeout=self._timeout) logger.warning("Created job {} for url {}.".format(job.id, url)) return urls
python
def recruit(self, n=1): 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 = generate_random_id() hit = generate_random_id() assignment = generate_random_id() ad_parameters = ( "recruiter={}&assignmentId={}&hitId={}&workerId={}&mode=sandbox" ) ad_parameters = ad_parameters.format(self.nickname, assignment, hit, worker) url = "{}/ad?{}".format(base_url, ad_parameters) urls.append(url) bot = factory(url, assignment_id=assignment, worker_id=worker, hit_id=hit) job = q.enqueue(bot.run_experiment, timeout=self._timeout) logger.warning("Created job {} for url {}.".format(job.id, url)) return urls
[ "def", "recruit", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Recruiting {} Bot participants\"", ".", "format", "(", "n", ")", ")", "factory", "=", "self", ".", "_get_bot_factory", "(", ")", "urls", "=", "[", "]", "q", "...
Recruit n new participant bots to the queue
[ "Recruit", "n", "new", "participant", "bots", "to", "the", "queue" ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L766-L787
13,294
Dallinger/Dallinger
dallinger/recruiters.py
BotRecruiter.notify_duration_exceeded
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
def notify_duration_exceeded(self, participants, reference_time): for participant in participants: participant.status = "rejected" session.commit()
[ "def", "notify_duration_exceeded", "(", "self", ",", "participants", ",", "reference_time", ")", ":", "for", "participant", "in", "participants", ":", "participant", ".", "status", "=", "\"rejected\"", "session", ".", "commit", "(", ")" ]
The bot participant has been working longer than the time defined in the "duration" config value.
[ "The", "bot", "participant", "has", "been", "working", "longer", "than", "the", "time", "defined", "in", "the", "duration", "config", "value", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L799-L805
13,295
Dallinger/Dallinger
dallinger/recruiters.py
MultiRecruiter.parse_spec
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) count = int(match.group(2)) recruiters.append((name, count)) return recruiters
python
def parse_spec(self): recruiters = [] spec = get_config().get("recruiters") for match in self.SPEC_RE.finditer(spec): name = match.group(1) count = int(match.group(2)) recruiters.append((name, count)) return recruiters
[ "def", "parse_spec", "(", "self", ")", ":", "recruiters", "=", "[", "]", "spec", "=", "get_config", "(", ")", ".", "get", "(", "\"recruiters\"", ")", "for", "match", "in", "self", ".", "SPEC_RE", ".", "finditer", "(", "spec", ")", ":", "name", "=", ...
Parse the specification of how to recruit participants. Example: recruiters = bots: 5, mturk: 1
[ "Parse", "the", "specification", "of", "how", "to", "recruit", "participants", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L832-L843
13,296
Dallinger/Dallinger
dallinger/recruiters.py
MultiRecruiter.recruiters
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 first one from the specification that hasn't already reached its quota. """ recruit_count = 0 while recruit_count <= n: counts = dict( session.query(Recruitment.recruiter_id, func.count(Recruitment.id)) .group_by(Recruitment.recruiter_id) .all() ) for recruiter_id, target_count in self.spec: remaining = 0 count = counts.get(recruiter_id, 0) if count >= target_count: # This recruiter quota was reached; # move on to the next one. counts[recruiter_id] = count - target_count continue else: # Quota is still available; let's use it. remaining = target_count - count break else: return num_recruits = min(n - recruit_count, remaining) # record the recruitments and commit for i in range(num_recruits): session.add(Recruitment(recruiter_id=recruiter_id)) session.commit() recruit_count += num_recruits yield by_name(recruiter_id), num_recruits
python
def recruiters(self, n=1): recruit_count = 0 while recruit_count <= n: counts = dict( session.query(Recruitment.recruiter_id, func.count(Recruitment.id)) .group_by(Recruitment.recruiter_id) .all() ) for recruiter_id, target_count in self.spec: remaining = 0 count = counts.get(recruiter_id, 0) if count >= target_count: # This recruiter quota was reached; # move on to the next one. counts[recruiter_id] = count - target_count continue else: # Quota is still available; let's use it. remaining = target_count - count break else: return num_recruits = min(n - recruit_count, remaining) # record the recruitments and commit for i in range(num_recruits): session.add(Recruitment(recruiter_id=recruiter_id)) session.commit() recruit_count += num_recruits yield by_name(recruiter_id), num_recruits
[ "def", "recruiters", "(", "self", ",", "n", "=", "1", ")", ":", "recruit_count", "=", "0", "while", "recruit_count", "<=", "n", ":", "counts", "=", "dict", "(", "session", ".", "query", "(", "Recruitment", ".", "recruiter_id", ",", "func", ".", "count"...
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 first one from the specification that hasn't already reached its quota.
[ "Iterator", "that", "provides", "recruiters", "along", "with", "the", "participant", "count", "to", "be", "recruited", "for", "up", "to", "n", "participants", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L845-L883
13,297
Dallinger/Dallinger
dallinger/recruiters.py
MultiRecruiter.open_recruitment
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: break if recruiter.nickname in messages: result = recruiter.recruit(count) recruitments.extend(result) else: result = recruiter.open_recruitment(count) recruitments.extend(result["items"]) messages[recruiter.nickname] = result["message"] remaining -= count if remaining <= 0: break logger.info( ( "Multi-recruited {} out of {} participants, " "using {} recruiters." ).format(n - remaining, n, len(messages)) ) return {"items": recruitments, "message": "\n".join(messages.values())}
python
def open_recruitment(self, n=1): logger.info("Multi recruitment running for {} participants".format(n)) recruitments = [] messages = {} remaining = n for recruiter, count in self.recruiters(n): if not count: break if recruiter.nickname in messages: result = recruiter.recruit(count) recruitments.extend(result) else: result = recruiter.open_recruitment(count) recruitments.extend(result["items"]) messages[recruiter.nickname] = result["message"] remaining -= count if remaining <= 0: break logger.info( ( "Multi-recruited {} out of {} participants, " "using {} recruiters." ).format(n - remaining, n, len(messages)) ) return {"items": recruitments, "message": "\n".join(messages.values())}
[ "def", "open_recruitment", "(", "self", ",", "n", "=", "1", ")", ":", "logger", ".", "info", "(", "\"Multi recruitment running for {} participants\"", ".", "format", "(", "n", ")", ")", "recruitments", "=", "[", "]", "messages", "=", "{", "}", "remaining", ...
Return initial experiment URL list.
[ "Return", "initial", "experiment", "URL", "list", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/recruiters.py#L885-L913
13,298
Dallinger/Dallinger
dallinger/heroku/clock.py
run_check
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_time, config) if timeline.is_overdue: print( "Error: participant {} with status {} has been playing for too " "long - their recruiter will be notified.".format(p.id, p.status) ) recruiters_with_late_participants[p.recruiter_id].append(p) for recruiter_id, participants in recruiters_with_late_participants.items(): recruiter = recruiters.by_name(recruiter_id) recruiter.notify_duration_exceeded(participants, reference_time)
python
def run_check(participants, config, reference_time): recruiters_with_late_participants = defaultdict(list) for p in participants: timeline = ParticipationTime(p, reference_time, config) if timeline.is_overdue: print( "Error: participant {} with status {} has been playing for too " "long - their recruiter will be notified.".format(p.id, p.status) ) recruiters_with_late_participants[p.recruiter_id].append(p) for recruiter_id, participants in recruiters_with_late_participants.items(): recruiter = recruiters.by_name(recruiter_id) recruiter.notify_duration_exceeded(participants, reference_time)
[ "def", "run_check", "(", "participants", ",", "config", ",", "reference_time", ")", ":", "recruiters_with_late_participants", "=", "defaultdict", "(", "list", ")", "for", "p", "in", "participants", ":", "timeline", "=", "ParticipationTime", "(", "p", ",", "refer...
For each participant, if they've been active for longer than the experiment duration + 2 minutes, we take action.
[ "For", "each", "participant", "if", "they", "ve", "been", "active", "for", "longer", "than", "the", "experiment", "duration", "+", "2", "minutes", "we", "take", "action", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/heroku/clock.py#L19-L35
13,299
Dallinger/Dallinger
dallinger/registration.py
register
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
def register(dlgr_id, snapshot=None): 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)
[ "def", "register", "(", "dlgr_id", ",", "snapshot", "=", "None", ")", ":", "try", ":", "config", ".", "get", "(", "\"osf_access_token\"", ")", "except", "KeyError", ":", "pass", "else", ":", "osf_id", "=", "_create_osf_project", "(", "dlgr_id", ")", "_uplo...
Register the experiment using configured services.
[ "Register", "the", "experiment", "using", "configured", "services", "." ]
76ca8217c709989c116d0ebd8fca37bd22f591af
https://github.com/Dallinger/Dallinger/blob/76ca8217c709989c116d0ebd8fca37bd22f591af/dallinger/registration.py#L15-L23