def test_survey_survey_set_criterion_invalid() -> None: """A test for set_criterion() in class Survey.""" q1 = CheckboxQuestion(1, 'ABC', ['a', '1', ',']) q2 = YesNoQuestion(2, 'BBC') s = Survey([q1]) c = HomogeneousCriterion() assert s.set_criterion(c, q2) is False
def test_survey_get_weight() -> None: q1 = CheckboxQuestion(1, "choose", [1, 2, 3, 4]) q2 = CheckboxQuestion(2, "choose", [1, 2, 3, 4]) q3 = CheckboxQuestion(3, "choose", [1, 2, 3, 4]) q_list = [q1, q2, q3] s = Survey(q_list) assert s._get_weight(q1) == 1
def _find_best_window(self, survey: Survey, windows_: List[List[Any]], lst_students: List[Student]) -> List: """" Return a list, first element is the new group to be added to window, second element is the new windows list """ for index, window in enumerate(windows_): if index + 1 == len(windows_): wind_curr_score = survey.score_students(window) wind_first = survey.score_students(windows_[0]) if wind_curr_score >= wind_first: new_lst = self._new_windows(window, lst_students) return [window, new_lst] else: window = windows_[0] new_lst = self._new_windows(window, lst_students) return [window, new_lst] else: wind_curr_score = survey.score_students(window) wind_next_score = survey.score_students(windows_[index + 1]) if wind_curr_score >= wind_next_score: new_lst = self._new_windows(window, lst_students) return [window, new_lst] return None
def testUpdateFromJson(self): s = Survey(eis_id='a', first_name='b', nbl_finish_timestamp=datetime.now(), survey_send_time=datetime.now() + timedelta(hours=24)) s.set_defaults() s.put() headAffected = True headPain = 5 j = { 'questions': { 'pain': True }, 'bodyparts': { 'head': { 'affected': headAffected, 'pain': headPain } } } s.update_from_json(j) s.put() head = '' for part in s.bodyparts: if part.name == 'head': head = part break self.assertEqual(s.pain, True) self.assertEqual(head.affected, headAffected) self.assertEqual(head.pain, headPain)
def test_survey_survey_get_questions() -> None: """A test for get_questions() in class Survey.""" q1 = CheckboxQuestion(1, 'ABC', ['a', '1', ',']) q2 = YesNoQuestion(2, 'BBC') s = Survey([q1, q2]) lst = s.get_questions() assert q1 in lst and q2 in lst
def main(): # create objects of questions and sections for servey qualify1 = Question('1', 'Question 1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) qualify2 = Question('2', 'Question 2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) qualify3 = Question('3', 'Question 3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q4 = Question('1', 'Question1 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q5 = Question('2', 'Question2 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q6 = Question('3', 'Question3 Section1 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q7 = Question('1', 'Question1 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q8 = Question('2', 'Question2 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q9 = Question('3', 'Question3 Section2 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q10 = Question('1', 'Question1 Section3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q11 = Question('2', 'Question2 Section3 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) q12 = Question('3', 'Question3 Section3 12 text? ', {'a': 'AnswerA', 'b': 'AnswerB', 'c': 'AnswerC'}) section_a = Section('SectionA Title', 'Here is some info about what we covered in section_a', [q4, q5, q6], qualify1) section_b = Section('SectionB Title', 'Here is some info about what we covered in section_b', [q7, q8, q9], qualify2) section_c = Section('SectionC Title', 'Here is some info about what we covered in section_c', [q10, q11, q12], qualify3) qualifyquestion = [qualify1, qualify2, qualify3] my_survey = Survey('SheCodes Survey', 'This is a placeholder for Description on Survey', qualifyquestion, [section_a, section_b, section_c]) my_survey.survey_introduction()
def _window_helper(self, lst_windows: list, survey: Survey, students: list, grouping: Grouping) -> None: ''' For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. ''' i = 0 found = False while i < len(lst_windows) and not found: window = lst_windows[i] score = survey.score_students(window) if i == len(lst_windows) - 1: next_score = survey.score_students(lst_windows[0]) else: next_score = survey.score_students(lst_windows[i + 1]) if score >= next_score: found = True group = Group(window) for member in window: students.remove(member) grouping.add_group(group) lst_windows = windows(students, self.group_size) else: i += 1
def createDummy(): survey = Survey(eis_id='123', first_name='Michael', nbl_finish_timestamp=datetime.fromtimestamp(1539546879), survey_send_time=datetime.fromtimestamp(1539719679)) survey.set_defaults() return survey.put().urlsafe()
def _sort_group(self, list_of_students: List[Student], survey: Survey) -> Group: """ Returns a Group of students with length equal or less than self.group_size. With a given list of Student: 1. select the first student in the list that hasn't already been put into a group and put this student in a new group_list. 2. select the student in the list that hasn't already been put into group_list that, if added to the new group, would increase the group's score the most (or reduce it the least), add that student to the new group_list. 3. repeat steps 1 - 2 until length of group_list is equal or less than self.group_size For every student added to group_list, they should also be removed from the original given list. === Precondition === <list_of_students> is not empty """ group_list = [list_of_students.pop(0)] score = 0.0 while (len(group_list) < self.group_size) and \ (len(list_of_students) != 0): best_student = list_of_students[0] for student in list_of_students: group_list.append(student) if survey.score_students(group_list) > score: score = survey.score_students(group_list) best_student = student group_list.remove(student) group_list.append(best_student) list_of_students.remove(best_student) return Group(group_list)
def testPostSurvey(self): # First create one data = { 'questions': { 'treatments': ['x'] }, 'bodyparts': { 'head': { 'cuts': True } } } j = json.dumps(data) # Create a survey to be updated s = Survey(eis_id='a', first_name='b', nbl_finish_timestamp=datetime.now(), survey_send_time=datetime.now() + timedelta(hours=24)) s.set_defaults() key = s.put().urlsafe() response = self.app.post('/api/survey/%s' % key, data=j) self.assertEqual(response.status_code, 200) self.assertEqual(ndb.Key(urlsafe=key).get().treatments, ['x'])
def test_survey_get_criterion() -> None: q1 = CheckboxQuestion(1, "choose", [1, 2, 3, 4]) q2 = CheckboxQuestion(2, "choose", [1, 2, 3, 4]) q3 = CheckboxQuestion(3, "choose", [1, 2, 3, 4]) q_list = [q1, q2, q3] s = Survey(q_list) assert isinstance(s._get_criterion(q1), HomogeneousCriterion)
def __init__(self): super().__init__("respond") # two for inserting new respond self.__mcq = RespondMcq() self.__text = RespondText() # check the type of question self.__survey = Survey() self.__question = Question()
def bigval(s: List[Student], lst: List[Student], survey: Survey) -> Any: bigval = -99999 big = None for i in lst: if survey.score_students(s + [i]) > bigval: big = i bigval = survey.score_students(s + [i]) return big
def testJsonify(self): s = Survey(eis_id='a', first_name='b', nbl_finish_timestamp=datetime.now(), survey_send_time=datetime.now() + timedelta(hours=24)) s.set_defaults() j = s.jsonify() self.assertIn('head', j['bodyparts']) self.assertIn('cuts', j['bodyparts']['head'])
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. select the first student in the tuple that hasn't already been put into a group and put this student in a new group. 2. select the student in the tuple that hasn't already been put into a group that, if added to the new group, would increase the group's score the most (or reduce it the least), add that student to the new group. 3. repeat step 2 until there are N students in the new group where N is equal to self.group_size. 4. repeat steps 1-3 until all students have been placed in a group. In step 2 above, use the <survey>.score_students method to determine the score of each group of students. The final group created may have fewer than N members if that is required to make sure all students in <course> are members of a group. """ grouping = Grouping() students = list(course.get_students()) lst = list() add_score = None next_student = None curr_score = 0.0 while len(students) > 0: if len(lst) == 0: student = students[0] lst.append(student) students.remove(student) curr_score = survey.score_students(lst) continue for student in students: lst.append(student) score = survey.score_students(lst) if add_score is None: add_score = score - curr_score next_student = student elif score - curr_score > add_score: add_score = score - curr_score next_student = student lst.remove(student) lst.append(next_student) if len(lst) == self.group_size or len(students) == 0: grouping.add_group(Group(lst)) lst = list() add_score = None next_student = None curr_score = 0.0 return grouping
def setUp(self): global survey survey = Survey() q = survey.add(Question(1, "Question1")) q.add(Answer(1, "answer1")) q.add(Answer(2, "answer2")) q = survey.add(Question(2, "Question2")) q.add(Answer(3, "answer3")) q.add(Answer(4, "answer4")) q.add(Answer(5, "answer5"))
def setUp(self): global survey survey = Survey() q = survey.add(Question(1,"Question1")) q.add(Answer(1,"answer1")) q.add(Answer(2,"answer2")) q = survey.add(Question(2,"Question2")) q.add(Answer(3,"answer3")) q.add(Answer(4,"answer4")) q.add(Answer(5,"answer5"))
def test_store_single_response(self): question = 'what language did you first learn to speak? ' my_survey = Survey(question) # my_survey.store_response('English') # self.assertIn('English', my_survey.responses) responses = ['english', 'chinese', 'japanese'] for res in responses: my_survey.store_response(res) for res in responses: self.assertIn(res, my_survey.responses)
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ if len(course.students) <= self.group_size: g = Grouping() group = Group(course.students.copy()) g.add_group(group) return g lst = course.students.copy() win = windows(lst, self.group_size) g = Grouping() while True: for i in range(0, len(win)): if i + 1 < len(win): if survey.score_students(win[i]) >= survey.score_students(win[i+1]): group = Group(win[i]) g.add_group(group) for p in win[i]: lst.remove(p) break else: group = Group(win[i]) g.add_group(group) for p in win[i]: lst.remove(p) break if len(lst) <= self.group_size: group = Group(lst) g.add_group(group) return g win = windows(lst, self.group_size)
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ # TODO: complete the body of this method stu = list(course.get_students()) g = Grouping() while len(stu) > self.group_size: wds = windows(stu, self.group_size) for i in range(len(wds)): curr_score1 = survey.score_students(wds[i]) if i == len(wds) - 1: idx_next = 0 else: idx_next = i + 1 curr_score2 = survey.score_students(wds[idx_next]) if curr_score1 >= curr_score2: g.add_group(Group(wds[i])) #remove students that are assigned group from the stu list for s in wds[i]: stu.remove(s) break if 0 < len(stu) <= self.group_size: g.add_group(Group(stu)) return g
class Collector: def __init__(self,phone,name): self.phone=phone self.name=name self.survey_list={} self.contact_list={} self.state=0; self.cur=None self.cur_question=None def create_Survey(self,name): self.cur=Survey(name) if self.cur is None: return -1 return 1 def add_question(self,question): if self.cur is not None: self.add_question(question) def process_response(self,input): if self.cur_question is None: self.cur_question=Question() self.cur_question.add_description(input) return 1 elif self.cur_question.get_type() is None: self.cur_question.set_type(input) return 2 else: self.cur_question.add_choice(input) return 2 def add_contact_list(self,phone_list): tmp=phone_list.split(",") name=str(tmp[0]).lower() for i in range(1,len(tmp)): self.contact_list[name].append(str(tmp[i])) def get_contact_list(self,name): return self.contact_list[name] def end_choice(self): self.cur.add_question(self.cur_question) self.cur_question=None def end_survey(self): self.survey_list[self.cur.get_name()]=self.cur self.cur=None def get_survey(self,name): return self.survey_list[name]
def testFetchSurvey(self): # First create one s = Survey(eis_id='a', first_name='b', nbl_finish_timestamp=datetime.now(), survey_send_time=datetime.now() + timedelta(hours=24)) s.set_defaults() key = s.put().urlsafe() response = self.app.get('/api/survey/%s' % key) data = json.loads(response.data) self.assertEqual(response.status_code, 200) self.assertEqual(data['eisId'], 'a')
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ # assuming list is sorted by id as per get_students() docstring all_students = list(course.get_students()) final_grouping = Grouping() while len(all_students) != 0: my_windows = windows(all_students, self.group_size) index_found = -1 i = 0 while i in range(len(my_windows) - 1) and index_found == -1: score_i = survey.score_students(my_windows[i]) score_j = survey.score_students(my_windows[i + 1]) if score_i >= score_j: index_found = i if index_found == -1: group_to_add = Group(my_windows[-1]) final_grouping.add_group(group_to_add) else: group_to_add = Group(my_windows[0]) final_grouping.add_group(group_to_add) for student in group_to_add.get_members(): all_students.remove(student) return final_grouping
def __init__(self, db): # inherit Survey class constructor Survey.__init__(self, db) # call Database connection from Survey class connection self.db = db self.conn = self.getConn() self.cur = self.conn.cursor() #output database connection print("\n",Survey.__str__(self))
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ grouping = Grouping() student_list = list(course.get_students()) while student_list != []: if len(student_list) < self.group_size: grouping.add_group(Group(student_list)) student_list = [] window = windows(student_list, self.group_size) window_length = len(window) for i in range(0, window_length): if i == (window_length - 1): win3 = survey.score_students(window[0]) win4 = survey.score_students(window[i]) if win4 >= win3: grouping.add_group(Group(window[i])) for j in range(0, len(window[i])): student_list.remove(window[i][j]) break win1 = survey.score_students(window[i]) win2 = survey.score_students(window[i + 1]) if win1 >= win2: grouping.add_group(Group(window[i])) for j in range(0, len(window[i])): student_list.remove(window[i][j]) break return grouping
def make_grouping(self, course: Course, survey: Survey) -> Grouping: """ Return a grouping for all students in <course>. Starting with a tuple of all students in <course> obtained by calling the <course>.get_students() method, create groups of students using the following algorithm: 1. Get the windows of the list of students who have not already been put in a group. 2. For each window in order, calculate the current window's score as well as the score of the next window in the list. If the current window's score is greater than or equal to the next window's score, make a group out of the students in current window and start again at step 1. If the current window is the last window, compare it to the first window instead. In step 2 above, use the <survey>.score_students to determine the score of each window (list of students). In step 1 and 2 above, use the windows function to get the windows of the list of students. If there are any remaining students who have not been put in a group after repeating steps 1 and 2 above, put the remaining students into a new group. """ grouping = Grouping() list_of_students = list(course.get_students()) list_of_groups = [] index = 0 windowed_list = windows(list_of_students, self.group_size) while index < len(windowed_list): if index + 1 == len(windowed_list): score1 = survey.score_students(windowed_list[index]) score2 = survey.score_students(windowed_list[0]) else: score1 = survey.score_students(windowed_list[index]) score2 = survey.score_students(windowed_list[index + 1]) if score1 >= score2: list_of_groups.append(windowed_list[index]) for student in windowed_list[index]: list_of_students.remove(student) windowed_list = windows(list_of_students, self.group_size) index = 0 elif score1 < score2: index += 1 for group in list_of_groups: grouping.add_group(Group(group)) if len(list_of_students) != 0: grouping.add_group(Group(list_of_students)) return grouping
def createSurvey(): allSessions = loadAllCourseObjects(server.coursesCSVReader) # Creates a list of sessionOffering objects for all sessions/courses if (request.method == "POST"): if (request.form["bt"] == "back"): return redirect(url_for("landing")) if (request.form["name"].strip() != ""): newSurvey = Survey(randomKey(), 0, 0, request.form["name"].strip(), request.form["description"], [0]) # Make the new survey object from HTML input fields writeSurvey(CSVWriter("csv/surveyform_"+newSurvey.getKey()+".csv"), server.qaaCSVReader, newSurvey, []) # Write a new survey form csv compoundKey = [allSessions[int(request.form["course"])].getName(), allSessions[int(request.form["course"])].getSession()] # Create the compound key required for search associateCourse(server.coursesCSVReader, server.coursesCSVWriter, compoundKey, newSurvey.getKey()) # Append the new survey onto its associated course return redirect(url_for("modifySurvey", key = newSurvey.getKey())) # Redirect to modify survey page after creation else: flash("Surveys must have a name and an associated course") # Flash user message for bad input return render_template("createSurvey.html", courses = allSessions, is_authenticated = server.user.getPermissions())
def __init__(self, **kwargs): global_idmap.update({'kivysurvey': self}) self.db_interface = DBInterface(self) super(KivySurvey, self).__init__(**kwargs) self.transition = SlideTransition() json = JsonStore(construct_target_file_name('survey.json', __file__)) for each in json: print(each) self.survey = Survey(json) try: gps.configure(on_location=self.receive_gps) except: pass Clock.schedule_once(self.start_gps)
def sendSurveys(): email_sender_address = Settings.get('email_sender_address') survey_link_base_url = Settings.get('survey_link_base_url') # first get surveys with survey_send_time < now AND # last_sent == null now = datetime.now() logging.info(now) # Currently only send to those who are due to be reminded AND have NOT # completed it AND have never received an email about this nbl run toSend = Survey.query(Survey.survey_send_time < now, Survey.send_count == 0, Survey.survey_complete_timestamp == None).fetch() logging.info('About to send %s emails' % len(toSend)) sent_keys = [] for survey in toSend: # create a link to the survey link = survey_link_base_url + survey.key.urlsafe() # mail it mail.send_mail(sender=email_sender_address, to="%s <%s>" % (survey.first_name, survey.email), subject="30-second NBL survey about your recent suit exposure", body=SURVEY_EMAIL.format(survey.first_name, link)) # mark it as sent with a timestamp survey.last_sent = datetime.now() # increment number times sent survey.send_count += 1 # save it sent_keys.append(survey.put().urlsafe()) logging.info('Sent the following keys: ') logging.info(sent_keys) return json.dumps(sent_keys)
def find_local_max_window(self, students_list: List[Student], survey: Survey) -> List[Student]: """ Find the first window of size group_size with the highest score before and after """ student_windows = windows(students_list, self.group_size) # For each window and index for i, window in enumerate(student_windows): # If we're at last window, this has to be max if i == len(student_windows) - 1: return window # Check score of current window and next one if survey.score_students(window) > survey.score_students( student_windows[i + 1]): return window
def setUp(self): """ Create a survey and a set of responses for use in all test methods. """ question = "What language did you first learn to speak?" self.my_survey = Survey(question) self.responses = ['English', 'Spanish', 'Mandarin']
def __init__(self): self.name = '2MASS' self.bands=['j','h','k'] self.color_bands=['j','h','k'] self.best_band ='k' #see Fig 2 (Skrutskie et al. 2006) self.pixel_scale = 2.0 self.data_server = Survey._initServer(self) # Mosaic Program Settings self.sextractor_params= " -PIXEL_SCALE {}".format(self.pixel_scale) self.stiff_param_low = " -MAX_TYPE QUANTILE -MAX_TYPE QUANTILE -MAX_LEVEL 0.997 -COLOUR_SAT 7 -MIN_TYPE QUANTILE -MIN_LEVEL 1 -GAMMA_FAC 0.7 " self.stiff_param_best = " -MAX_TYPE QUANTILE -MAX_LEVEL 0.99 -COLOUR_SAT 5 -MIN_TYPE QUANTILE -MIN_LEVEL 1 -GAMMA_FAC 0.8"
def run(pop, surveyList, nostdout=False, allsurveyfile=False, scint=False): """ Run the surveys and detect the pulsars.""" # print the population if not nostdout: print "Running doSurvey on population..." print pop # loop over the surveys we want to run on the pop file surveyPops = [] for surv in surveyList: s = Survey(surv) s.discoveries = 0 if not nostdout: print "\nRunning survey {0}".format(surv) # create a new population object to store discovered pulsars in survpop = Population() # HERE SHOULD INCLUDE THE PROPERTIES OF THE ORIGINAL POPULATION # counters nsmear = 0 nout = 0 ntf = 0 ndet = 0 # loop over the pulsars in the population list for psr in pop.population: # pulsar could be dead (evolve!) - continue if so if psr.dead: continue # is the pulsar over the detection threshold? snr = s.SNRcalc(psr, pop) # add scintillation, if required # modifying S/N rather than flux is sensible because then # a pulsar can have same flux but change S/N in repeated surveys if scint: snr = s.scint(psr, snr) if snr > s.SNRlimit: ndet += 1 psr.snr = snr survpop.population.append(psr) # check if the pulsar has been detected in other # surveys if not psr.detected: # if not, set to detected and increment # number of discoveries by the survey psr.detected = True s.discoveries += 1 elif snr == -1.0: nsmear += 1 elif snr == -2.0: nout += 1 else: ntf += 1 # report the results if not nostdout: print "Number detected by survey {0} = {1}".format(surv,ndet) print "Of which are discoveries = {0}".format(s.discoveries) print "Number too faint = {0}".format(ntf) print "Number smeared = {0}".format(nsmear) print "Number out = {0}".format(nout) print "\n" d = Detections(ndet=ndet, ntf=ntf, nsmear=nsmear, nout=nout, ndisc=s.discoveries) surveyPops.append([surv,survpop,d]) if allsurveyfile: allsurvpop = Population() allsurvpop.population = [psr for psr in pop.population if psr.detected] surveyPops.append([None, allsurvpop, None]) return surveyPops
#!/usr/bin/python from common.logger import setup_logging from survey import Survey setup_logging() if __name__ == '__main__': # Script to create a mosaic of unabsorbed HI and # a corresponding mosaic of column density # Canadian Galactic Plane Survey cgps = Survey('CGPS', 'HI', 'MW2', False) # Create an object (HI or CO, according to the above line) cgps.make_obs() # Generate mosaics of 'HI' (unabsorbed) or 'HISA' or 'WCO' # cgps.generate_mosaic(species='HI') # Load new mosaic # cgps.load_mosaic(species='HI', mtype='brightness_temperature') # Calculate the column density cgps.get_column_density(species='HI')
class KivySurvey(ScreenManager): current_page = ObjectProperty(None, allownone=True) current_subjects = ListProperty(None, allownone=True) db_interface = ObjectProperty(None) current_subjects = ListProperty(None, allownone=True) subject_id = NumericProperty(None, allownone=True) previous_subject_ids = ListProperty(None, allownone=True) current_page = ObjectProperty(None, allownone=True) current_subjects_page = ObjectProperty(None, allownone=True) next_page = StringProperty(None, allownone=True) prev_page = StringProperty(None, allownone=True) survey = ObjectProperty(None) current_location = DictProperty({}) gps_loc_interval = NumericProperty(30.0) questionnaire = StringProperty(None, allownone=True) top_level_questionnaire = StringProperty(None, allownone=True) root = ObjectProperty(None) def __init__(self, **kwargs): global_idmap.update({'kivysurvey': self}) self.db_interface = DBInterface(self) super(KivySurvey, self).__init__(**kwargs) self.transition = SlideTransition() json = JsonStore(construct_target_file_name('survey.json', __file__)) for each in json: print(each) self.survey = Survey(json) try: gps.configure(on_location=self.receive_gps) except: pass Clock.schedule_once(self.start_gps) def on_subject_id(self, instance, value): self.load_subjects(value, self.questionnaire) def create_subject(self): db_interface = self.db_interface uid = db_interface.get_unique_id() prev_id = self.previous_subject_ids[-1] db_interface.add_subject(prev_id, self.questionnaire, uid) return uid def pop_subjects(self): previous_subject_ids = self.previous_subject_ids if len(previous_subject_ids) > 0: self.subject_id = self.previous_subject_ids.pop() else: self.subject_id = None def on_questionnaire(self, instance, value): self.load_subjects(self.subject_id, value) self.current_subjects_page.allow_add_subject = ( self.survey.get_allow_add_subjects(value)) def load_subjects(self, subject_id, questionnaire): self.current_subjects = self.db_interface.get_subjects( subject_id, questionnaire) def get_header_lines(self): return self.survey.get_header_definitions(self.questionnaire) def set_next_page(self): survey = self.survey next_page = survey.get_next_page( self.questionnaire, self.current_page.page) if next_page is None: return False else: self.next_page = None self.next_page = next_page return True def add_member(self): self.transition.direction = 'left' self.previous_subject_ids.append(self.subject_id) self.subject_id = None self.reset_questionnaire() def open_member(self, member_id, instance): self.transition.direction = 'left' self.previous_subject_ids.append(self.subject_id) self.subject_id = member_id self.reset_questionnaire() current_page = self.current_page.ids.questions current_page.load_page_data() def reset_questionnaire(self): self.current_page.page = None self.set_next_page() self.swap_pages() self.current_page.ids.questions.clear_questions() def set_prev_page(self): survey = self.survey prev_page = survey.get_prev_page( self.questionnaire, self.current_page.page) if prev_page is None: return False else: self.prev_page = prev_page return True def swap_subjects(self): subjects1 = self.ids.subjects1 subjects2 = self.ids.subjects2 current_subjects_page = self.current_subjects_page if current_subjects_page is subjects1: self.current = 'subjects2' self.current_subjects_page = subjects2 elif current_subjects_page is subjects2: self.current = 'subjects1' self.current_subjects_page = subjects1 self.current_subjects_page.allow_add_subject = ( self.survey.get_allow_add_subjects(self.questionnaire)) self.current_page.ids.scrollview.scroll_to_top() def swap_pages(self): questions1 = self.ids.questions1 questions2 = self.ids.questions2 current_page = self.current_page if current_page is questions1: self.current = 'questions2' self.current_page = questions2 questions1.page = None elif current_page is questions2: self.current = 'questions1' self.current_page = questions1 questions2.page = None self.current_page.ids.scrollview.scroll_to_top() def on_next_page(self, instance, value): questions1 = self.ids.questions1 questions2 = self.ids.questions2 current_page = self.current_page if current_page is questions1: questions2.page = value elif current_page is questions2: questions1.page = value def on_prev_page(self, instance, value): questions1 = self.ids.questions1 questions2 = self.ids.questions2 current_page = self.current_page if current_page is questions1: questions2.page = value elif current_page is questions2: questions1.page = value def start_questionnaire(self, questionnaire): self.current_page.page = None self.swap_subjects() self.questionnaire = questionnaire self.set_next_page() def save_page(self): current_page = self.current_page.ids.questions current_page.save_page_data() def go_back(self): does_page_exist = self.set_prev_page() survey = self.survey questionnaire = self.questionnaire prev_questionnaire = survey.get_previous_questionnaire() self.transition.direction = 'right' if self.current in ['subjects1', 'subjects2']: if prev_questionnaire is None: self.app.root.change_screen('cluster', go_back=True) return else: if survey.get_allow_add_subjects(questionnaire): self.pop_subjects() self.start_questionnaire(survey.pop_previous_questionnaire()) elif does_page_exist: self.swap_pages() else: if self.subject_id is None: self.pop_subjects() self.swap_subjects() else: self.pop_subjects() self.swap_subjects() def go_forward(self): does_page_exist = self.set_next_page() survey = self.survey questionnaire = self.questionnaire next_questionnaire = survey.get_next_questionnaire(questionnaire) self.transition.direction = 'left' if self.current in ['subjects1', 'subjects2']: if next_questionnaire is None: if survey.get_allow_add_subjects(questionnaire): self.pop_subjects() prev_questionnaire = survey.pop_previous_questionnaire() self.start_questionnaire(prev_questionnaire) else: if survey.get_allow_forward(questionnaire): survey.store_current_questionnaire(questionnaire) self.start_questionnaire(next_questionnaire) elif does_page_exist: self.save_page() self.swap_pages() else: is_creating_subject = False if survey.get_allow_add_subjects(questionnaire) and ( self.subject_id is None): self.subject_id = self.create_subject() self.save_page() if next_questionnaire is None: self.pop_subjects() prev_questionnaire = survey.pop_previous_questionnaire() self.start_questionnaire(prev_questionnaire) elif survey.get_allow_add_subjects(next_questionnaire): survey.store_current_questionnaire(questionnaire) self.start_questionnaire(next_questionnaire) else: self.pop_subjects() self.swap_subjects() def start_gps(self, dt): try: gps.start() except: pass def receive_gps(self, **kwargs): if kwargs is not {}: self.current_location = kwargs gps.stop() Clock.schedule_once(self.start_gps, self.gps_loc_interval) def raise_error(self, error_title, error_text): self.app.raise_error(error_title, error_text) def raise_option_dialogue(self, option_title, option_text, options, callback): self.app.raise_option_dialogue(option_title, option_text, options, callback) def raise_numpad(self, numpad_title, callback, units=None, minimum=None, maximum=None, do_decimal=False): self.app.raise_numpad(numpad_title, callback, units, minimum, maximum, do_decimal)
class QSurveyGridShow(QtGui.QMainWindow): def __init__(self, survey): super(QSurveyGridShow, self).__init__() sg = QSurveyGrid(survey) self.setCentralWidget(sg) self.setWindowTitle("Survey Grid") self.show() if __name__ == "__main__": import sys from translation import loadTranslation from survey import Survey from question import Question from answer import Answer s = Survey("Survey Grid Test") q = s.add(Question(1,"Question1")) q.add(Answer(1,"answer1")) q.add(Answer(2,"answer2")) q = s.add(Question(2,"Question2")) q.add(Answer(3,"answer3")) q.add(Answer(4,"answer4")) q.add(Answer(5,"answer5")) loadTranslation("en") app = QtGui.QApplication(sys.argv) survey_grid = QSurveyGridShow(s) survey_grid.setGeometry(200, 100, 800, 600) sys.exit(app.exec_())