Пример #1
0
class Main:
    __doc__ = "Manages the user inputs and everything related to what is " \
              "shown to the user."

    def __init__(self):
        app_title()
        self.run = True
        self.subject = Subject()

    # To prompt the user to choose from menu selection
    def get_user_choice(self):
        while self.run:
            user_menu()
            choice = int(input("Choice: "))
            if choice not in range(1, 8):
                print('Wrong choice!')
            elif choice == 1:
                print("Show Schedule")
            elif choice == 2:
                print("Show Agenda")
            elif choice == 3:
                print("Add Homework/Quiz")
            elif choice == 4:
                print("Add Schedule")
            elif choice == 5:
                subject_id = input("Enter the Subject Id: ")
                self.subject.get_subject(subject_id)
            elif choice == 6:
                self.subject.add_subject()
            elif choice == 7:
                print("Thank you for using our Program!See you soon")
                break
Пример #2
0
def student_history_ranking(student_id: int) -> dict:
    result = {}
    result_chart = {}
    grades = StudentGrade.query.filter_by(
        student_ID=student_id, subject='理科').order_by(StudentGrade.test_time).all()
    test_names = [t.test_name for t in Test.query.order_by(Test.test_time).all()]
    print(test_names)
    for subject in Subject.li_all_subject():
        result[subject] = []
        for grade in grades:
            grade: StudentGrade
            result[subject].append(grade.__dict__[subject + '_ranking'])
    for subject in Subject.li_all_subject():
        line = (
            Line()
                .add_xaxis(test_names)
                .add_yaxis(
                '排名',
                result[subject],
                markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]), )
                .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=Subject.en2cn(subject) + '科历次成绩走势',
                    subtitle='虚线为平均排名'
                ),
            )
        )
        result_chart[subject] = line
    return result_chart
Пример #3
0
def student_grade_compared(student_grade: StudentGrade) -> Bar:
    """
    生成该考生本次考试的成绩对比条形图。
    :param student_grade:本次考试成绩StudentGrade对象
    :return: bar:Bar对象
    """
    data = {'student_grade': [], 'average_grade': [], 'high_grade': []}
    subjects = Subject.subjects_by_grade(student_grade)
    for subject in subjects:
        data['student_grade'].append(student_grade.grade_dict()[subject])
        data['average_grade'].append(TestAverageGrade.query.filter_by(
            subject='理科', test_time=student_grade.test_time).first()
                                     .grade_dict()[subject])
        data['high_grade'].append(TestHighGrade.query.filter_by(
            subject='理科', test_time=student_grade.test_time).first()
                                  .grade_dict()[subject])

    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))
            .add_xaxis(subjects)
            .add_yaxis('本次成绩', data['student_grade'])
            .add_yaxis('平均分', data['average_grade'])
            .add_yaxis('高分线', data['high_grade'])
            .set_global_opts(title_opts=opts.TitleOpts('成绩对比图'))
    )
    return bar
Пример #4
0
def read_sub_file():
    """Reads the custom_subjects.txt and generates a list of Subject objects of
       all subjects mentioned in the file.
    """
    sub_week = [
        [],  # Monday
        [],  # Tuesday
        [],  # Wednesday
        [],  # Thursday
        [],  # Friday
        [],  # Saturday
        []
    ]  # Sunday
    with open("custom_subjects.txt") as file:
        lines = file.readlines()
    day = 0
    for line in lines:
        if line[0].isdigit():
            day = int(line[0])
        elif line[0] == '$':
            line_array = (line.replace("$",
                                       "").replace("<",
                                                   "").replace(">",
                                                               "").split("_"))
            sub_week[day].append(
                Subject(
                    line_array[0],  # name
                    day_diff(day),  # submit
                    line_array[1],  # time
                    day_diff(int(line_array[2])),  # next_paper
                    line_array[3]))  # link
    return sub_week
Пример #5
0
def main():


	subjectApp = subInfo(0)
	subjectApp.MainLoop()

	pygame.init()
	screen = get_default_screen()
	screen.parameters.bgcolor = (0.0,0.0,0.0,0.0)
	pygame.display.set_caption("Welcome to the Experiment")

	global dataList

	dataList = []
	
	myList, justWords, followWords = bailey_shuffler.makeStroopList()

	print len(myList)
	print len(justWords)
	print len(followWords)

	for item in myList:
		showStimulus(screen, item[0][1], item[1])

	#now we need to make a list of the words with some distractors
	global memoryList

	memoryList = bailey_shuffler.makeDistractorList(justWords, followWords)
	
	#now we launch our wx App
	memoryApp = memApp(0)
	memoryApp.MainLoop()

	myloader = Subject.SubLoader()

	sub = myloader.load()

	filename = os.path.join(sub.path, (sub.name + "_stroop_data.pck"))

	textfile = os.path.join(sub.path, (sub.name + "_stroop_data.txt"))

	f = open(filename, 'w')

	pickle.dump(dataList, f)

	f.close()

	f = open(textfile, 'w')
	
	for line in dataList:
		f.write(str(line)+ "\n")

	f.close()

	stroop_stats.addSubData(sub)

	#stroop_stats.writeAllSubjects()

	stroop_stats.addSubMemoryData(sub)
Пример #6
0
Файл: Test.py Проект: 0x587/GA
def test_avg_grade_compare(test_time: int) -> dict:
    """
    :param test_time:
    :return: charts:{subject:chart,,,} example:{'english':chart1,'chinese':chart2,,,}
    """
    result = {}
    avg_grades = ClassAverageGrade.query.filter_by(
        test_time=test_time,
        subject='理科').order_by(ClassAverageGrade.class_index).all()
    test_avg_grade = TestAverageGrade.query.filter_by(test_time=test_time,
                                                      subject='理科').first()
    for subject in Subject.li_all_subject():
        avg = test_avg_grade.grade_dict()[subject]
        chart = (Bar(init_opts=opts.InitOpts(
            theme=ThemeType.VINTAGE)).add_xaxis([
                '{}班'.format(i + 1) for i in range(17)
            ]).add_yaxis(
                '平均分',
                [round(ag.grade_dict()[subject], 1) for ag in avg_grades],
                yaxis_index=0).add_yaxis(
                    '平均分差',
                    [
                        round(ag.grade_dict()[subject] - avg, 1)
                        for ag in avg_grades
                    ],
                    yaxis_index=1,
                ).set_global_opts(
                    yaxis_opts=opts.AxisOpts(name='均分',
                                             axislabel_opts=opts.LabelOpts(
                                                 formatter='{value}分')),
                    xaxis_opts=opts.AxisOpts(axisline_opts=opts.AxisLineOpts(
                        on_zero_axis_index=1)),
                    datazoom_opts=[
                        opts.DataZoomOpts(type_='slider',
                                          range_start=5,
                                          range_end=55),
                        opts.DataZoomOpts(type_='inside')
                    ],
                    title_opts=opts.TitleOpts(title='各班{}均分对比图'.format(
                        Subject.en2cn(subject)))).extend_axis(
                            yaxis=opts.AxisOpts(name='均分差',
                                                axislabel_opts=opts.LabelOpts(
                                                    formatter='{value}分'))))
        result[subject] = chart
    return result
Пример #7
0
def GenerateExaminationPaper():
    examinationQuestions = []
    subjects = []
    questionsPerSubject = 30
    mathematics = Subject.Subject("mathematics")
    subjects.append(mathematics)
    physics = Subject.Subject("physics")
    subjects.append(physics)
    chemistry = Subject.Subject("chemistry")
    subjects.append(chemistry)
    mathematicsQuestions = GenerateSubjectPaper(mathematics,
                                                questionsPerSubject)
    physicsQuestions = GenerateSubjectPaper(physics, questionsPerSubject)
    chemistryQuestions = GenerateSubjectPaper(chemistry, questionsPerSubject)
    examinationQuestions.extend(mathematicsQuestions)
    examinationQuestions.extend(physicsQuestions)
    examinationQuestions.extend(chemistryQuestions)
    return examinationQuestions, subjects
Пример #8
0
  def cmd_subject_add( self, item, args, rawline ):
    """-n <name> -s <shortcut>|-i||add a new subject. Argument -n is to pass a name and -s to pass a shortcut and -i for interactive mode"""
    parser = argparse.ArgumentParser( prog = "subject add", description = self.cmd_subject_add.__doc__.split( "||" )[1] )
    parser.add_argument( "-n", "--name", help = "set the name of the new subject" )
    parser.add_argument( "-s", "--shortcut", help = "set the shortcut of the new subject" )
    parser.add_argument( "-i", "--interactive", action = "store_true", help = "use the interactive mode" )

    try:
      parsed_args = parser.parse_args( args.split( " " ))
      name     = ""
      shortcut = ""
      save     = True
      if parsed_args.interactive:
        try:
          while name == "":
            name = input( "Name: " )
          while shortcut == "":
            shortcut = input( "Shortcut: " )
          save = input( "Do you want to save ([y]/n)? " )
          save = (save == "y" or save == "")
        except KeyboardInterrupt:
          save = False
          print( "" ) # To break down prompt to a new line
      elif parsed_args.name is not None and parsed_args.name != "" and parsed_args.shortcut is not None and parsed_args.shortcut != "":
        name     = parsed_args.name
        shortcut = parsed_args.shortcut
      else:
        save = False
      if save:
        subject          = Subject( self._connection )
        subject.Name     = name
        subject.Shortcut = shortcut
        if subject.Insert( ):
          cf.out.bold_green( "Subject with name `{} ({})` has been successfully saved!".format( name, shortcut ))
          cf.out.white( "If you want to link this subject with the current term you have to execute `subject link`" )
          self._UpdateCDCommand( )
        else:
          cf.out.bold_red( "An error occured during the insert action of subject with name `{}`".format( name ))
      elif parsed_args.name is None or parsed_args.name == "" or parsed_args.shortcut is None or parsed_args.shortcut == "":
        cf.out.bold_red( "You have to pass a name with -n and a shortcut with -s to save a subject else you can choose -i for interactive mode" )
    except SystemExit:       # Do not exit cli if an error occured in parse_args
      pass
Пример #9
0
def test_total_table_data(test_time: int):
    test = Test.query.filter_by(test_time=test_time).first()
    grades = StudentGrade.query.filter_by(test_time=test_time,
                                          subject='理科').all()
    result = {'code': 0, 'msg': '', 'data': [{} for _ in range(11)]}

    test_avg_grade = TestAverageGrade.query.filter_by(test_time=test_time,
                                                      subject='理科').first()

    for subject in Subject.li_all_subject():
        scores = [grade.grade_dict()[subject] for grade in grades]
        result['data'][0][subject] = Subject.subject_full_grade(subject)
        result['data'][1][subject] = len(test.student_grades)
        result['data'][2][subject] = test_avg_grade.grade_dict()[subject]
        result['data'][3][subject] = 'To be developed'
        result['data'][4][subject] = 'To be developed'
        result['data'][5][subject] = np.max(scores)
        result['data'][6][subject] = np.min(scores)
        result['data'][7][subject] = np.std(scores).round(1)
        result['data'][8][subject] = '{}%'.format((GradeRanking.grade_rate(
            scores,
            Subject.subject_full_grade(subject) * 0.9) * 100).__round__(1))
        result['data'][9][subject] = '{}%'.format((GradeRanking.grade_rate(
            scores,
            Subject.subject_full_grade(subject) * 0.8) * 100).__round__(1))
        result['data'][10][subject] = '{}%'.format((GradeRanking.grade_rate(
            scores,
            Subject.subject_full_grade(subject) * 0.6) * 100).__round__(1))

    result['data'][0]['key'] = '卷面分'
    result['data'][1]['key'] = '参考人数'
    result['data'][2]['key'] = '年级平均分'
    result['data'][3]['key'] = '普通班平均分'
    result['data'][4]['key'] = '实验班平均分'
    result['data'][5]['key'] = '最高分'
    result['data'][6]['key'] = '最低分'
    result['data'][7]['key'] = '标准差'
    result['data'][8]['key'] = '优秀率'
    result['data'][9]['key'] = '良好率'
    result['data'][10]['key'] = '及格率'
    return json.dumps(result)
Пример #10
0
 def loadFromFile(self, name):
     assert isinstance(name, str)
     file = open(name)
     input = file.read()
     splitted = str.split(input, '\n')
     for entry in splitted:
         entrySplitted = str.split(entry, ', ')
         if len(entrySplitted) == 1:
             continue
         surname = entrySplitted[0]
         name = entrySplitted[1]
         student = Student(name, surname)
         subentries = entrySplitted[2:]
         for sub in subentries:
             subentrySplitted = str.split(sub, ' ')
             subject = Subject(subentrySplitted[0])
             for grade in subentrySplitted[1:]:
                 subject.AddGrade(float(grade))
             student.AddSubject(subject)
         self.listOfStudents.append(student)
     file.close()
Пример #11
0
Файл: Test.py Проект: 0x587/GA
def test_grade_distributed(test_time: int) -> list:
    grades = StudentGrade.query.filter_by(test_time=test_time,
                                          subject='理科').all()
    result = [{} for _ in range(15)]

    for subject in Subject.li_all_subject(False):
        scores = [grade.grade_dict()[subject] for grade in grades]
        for i in range(15):
            result[14 - i][subject] = len(
                [_ for _ in scores if i * 10 < _ < i * 10 + 10])

    for i in range(15):
        result[14 - i]['key'] = '{}分—{}分段'.format(i * 10, i * 10 + 10)
    return result
Пример #12
0
def analysis_test():
    for test in Test.query.all():
        for subject_class in ['文科', '理科']:
            average_grade = TestAverageGrade(test)
            average_grade.subject = subject_class
            high_grade = TestHighGrade(test)
            high_grade.subject = subject_class
            db.session.add(average_grade)
            db.session.add(high_grade)
            grades = StudentGrade.query.filter_by(
                subject=subject_class, test_time=test.test_time).all()
            if subject_class == '文科':
                subjects = Subject.wen_all_subject(True)
            else:
                subjects = Subject.li_all_subject(True)
            for subject in subjects:
                grade_array = np.array(
                    [g.grade_dict()[subject] for g in grades])
                average_grade.set_grade(
                    subject, float(round(np.average(grade_array), 2)))
                average_grade.set_ranking(
                    subject,
                    grade2ranking(test,
                                  int(np.average(grade_array)),
                                  subject=subject,
                                  subject_type=subject_class))
                high_grade.set_grade(
                    subject,
                    float(round(np.percentile(grade_array, high_line), 2)))
                high_grade.set_ranking(
                    subject,
                    grade2ranking(test,
                                  int(np.percentile(grade_array, high_line)),
                                  subject=subject,
                                  subject_type=subject_class))
            db.session.commit()
Пример #13
0
	def onOK(self, event):
		if self.male.GetValue():
			sex = 2
		else:
			sex = 1
		if self.left.GetValue():
			hand = 1		
		else:
			hand = 2
		
		sub = Subject.Subject(self.number.GetValue(), sex, hand)

		sub.save()

		self.Destroy()
Пример #14
0
	def addSubject(self, behaviorToAssign = None):
		"""
		 Adds a new subject to this layer.

		@param Behavior behaviorToAssign : The behavior that should be assigned to the subject.
		@return Subject :
		@author
		"""
		if((behaviorToAssign is not None) and (not isinstance(behaviorToAssign, Behavior))):
			raise Exception("'BehaviorToAssign' must be of type Behavior!")
		if(behaviorToAssign is None):
			behaviorToAssign = self.addBehavior()
		newSubject = Subject(self.modelManager, behavior=behaviorToAssign)
		self.hasModelComponent.append(newSubject)
		return newSubject
Пример #15
0
def student_grade_radar(student_grade: StudentGrade) -> Radar:
    """
    生成该考生本次考试的排名雷达图。
    :param student_grade: 本次考试成绩StudentGrade对象
    :return: radar: Radar图表
    """
    subjects = Subject.subjects_by_grade(student_grade)
    data = {'student_ranking': [], 'average_ranking': [], 'high_ranking': []}
    for subject in subjects:
        data['student_ranking'].append(
            GradeRanking.grade2ranking(
                student_grade.test,
                student_grade.grade_dict()[subject], subject, student_grade.subject))
        data['average_ranking'].append(TestAverageGrade.query.filter_by(
            subject='理科', test_time=student_grade.test_time).first()
                                       .__dict__[subject + '_ranking'])
        data['high_ranking'].append(TestHighGrade.query.filter_by(
            subject='理科', test_time=student_grade.test_time).first()
                                    .__dict__[subject + '_ranking'])
    radar = (
        Radar(init_opts=opts.InitOpts(bg_color='#fef8ef'))
            .add_schema(
            schema=[
                opts.RadarIndicatorItem(
                    name=subject,
                    color='#778899',
                    max_=max(
                        data['student_ranking'] + data['average_ranking'] + data['high_ranking']) + 50
                ) for subject in subjects
            ],
            textstyle_opts=opts.TextStyleOpts(font_size=18)
        )
            .set_global_opts(title_opts=opts.TitleOpts('名次雷达图'), )
            .set_series_opts()
            .add('本次排名', [data['student_ranking']], color='#d7ab82',
                 linestyle_opts=opts.LineStyleOpts(width=2.5),
                 label_opts=opts.LabelOpts(is_show=True, font_size=14),
                 tooltip_opts=opts.TooltipOpts(is_show=False))
            .add('平均排名', [data['average_ranking']], color='#919e8b',
                 linestyle_opts=opts.LineStyleOpts(width=2.5),
                 label_opts=opts.LabelOpts(is_show=True, font_size=14),
                 tooltip_opts=opts.TooltipOpts(is_show=False))
            .add('高分线排名', [data['high_ranking']], color='#d87c7c',
                 linestyle_opts=opts.LineStyleOpts(width=2.5),
                 label_opts=opts.LabelOpts(is_show=True, font_size=14),
                 tooltip_opts=opts.TooltipOpts(is_show=False))
    )
    return radar
Пример #16
0
def main():

    subjectApp = subInfo(0)
    subjectApp.MainLoop()

    pygame.init()
    screen = get_default_screen()
    screen.parameters.bgcolor = (0.0, 0.0, 0.0, 0.0)
    pygame.display.set_caption("Welcome to the Experiment")

    global dataList

    dataList = []

    myList, justWords, followWords = bailey_shuffler.makeClassicStroop()

    print len(myList)
    print len(justWords)
    print len(followWords)

    for item in myList:
        showStimulus(screen, item[0], item[1])

    myloader = Subject.SubLoader()

    sub = myloader.load()

    filename = os.path.join(sub.path, (sub.name + "_color_data.pck"))

    textfile = os.path.join(sub.path, (sub.name + "_color_data.txt"))

    f = open(filename, 'w')

    pickle.dump(dataList, f)

    f.close()

    f = open(textfile, 'w')

    for line in dataList:
        f.write(str(line) + "\n")

    f.close()

    stroop_stats.addSubColorData(sub)
Пример #17
0
async def addData(message: types.Message):
    data = message.text[5:].split(' ')
    task = ""
    for word in data:
        if word != data[0]:
            task += word + " "
    if not data or not task:
        await message.answer("Incorrect input for /add command, use /help")
    else:
        subject = Subject.Subject(data[0], None, task, None)
        try:
            Storage.AddSub(message.from_user.id, subject)
            await message.answer("your task was inserted\n\n" + task + "\nfor subject: " + data[0])
        except AppExceptions.Not_Enough_Data as error:
            print(error)
            print("Incorrect input for /add command, use /help")
        except Exception as e:
            print(e)
            print("Error can not insert your data")
Пример #18
0
def readFromFile(filename):
    book = xw.Book(filename)
    sht = book.sheets[0].range('A1').expand().value
    sht = [list(map(str, row)) for row in sht]
    teachers = []
    subjects = []
    app = xw.apps.active

    for i in range(1, len(sht)):
        teachers.append(
            Teacher(int(float(sht[i][0])), list(map(int,
                                                    sht[i][1].split(';'))),
                    list(map(int, sht[i][2].split(';'))),
                    int(float(sht[i][3]))))
    sht = book.sheets[1].range('A1').expand().value
    for i in range(1, len(sht)):
        subjects.append(
            Subject(int(float(sht[i][0])), sht[i][1], int(float(sht[i][2]))))
    app.quit()
    return (teachers, subjects)
Пример #19
0
def readFromFile(filename):
    book = xw.load_workbook('data.xlsx', data_only=True)
    sht = book.worksheets[0]
    # sht = [list(map(str,row)) for row in sht]
    teachers = []
    subjects = []
    # app = xw.apps.active

    for i in range(2, 15):
        teachers.append(
            Teacher(int(float(sht[i][0].value)),
                    list(map(int, sht[i][1].value.split(';'))),
                    list(map(int, sht[i][2].value.split(';'))),
                    int(float(sht[i][3].value))))

    sht = book.worksheets[1]

    for i in range(2, 15):
        subjects.append(
            Subject(int(float(sht[i][0].value)), sht[i][1].value,
                    int(float(sht[i][2].value))))

    return (teachers, subjects)
Пример #20
0
def student_grade_analysis_table_data(grade_id: int):
    result = {'code': 0, 'msg': '', 'data': [{} for _ in range(7)]}

    grade = StudentGrade.query.filter_by(ID=grade_id).first()

    test_avg_grade = TestAverageGrade.query.filter_by(
        test_time=grade.test_time, subject='理科').first()

    test_high_grade = TestHighGrade.query.filter_by(test_time=grade.test_time,
                                                    subject='理科').first()

    class_grade = ClassAverageGrade.query.filter_by(
        test_time=grade.test_time,
        class_index=grade.class_index,
    ).first()

    for subject in Subject.li_all_subject():
        result['data'][0][subject] = grade.grade_dict()[subject]
        result['data'][1][subject] = class_grade.grade_dict()[subject]
        result['data'][2][
            subject] = GradeRanking.grade2ranking_with_grade_for_class(
                grade_id, subject)
        result['data'][3][subject] = test_avg_grade.grade_dict()[subject]
        result['data'][4][subject] = GradeRanking.grade2ranking_with_grade(
            grade_id, subject)
        result['data'][5][subject] = 'To be developed'
        result['data'][6][subject] = test_high_grade.grade_dict()[subject]

    result['data'][0]['key'] = '分数'
    result['data'][1]['key'] = '班级平均分'
    result['data'][2]['key'] = '班级名次'
    result['data'][3]['key'] = '年级平均分'
    result['data'][4]['key'] = '年级名次'
    result['data'][5]['key'] = '进退步'
    result['data'][6]['key'] = '重点线'
    return json.dumps(result)
def MenuSubject():
	while True:
		print("\t\t\t Subject Record Management\n")
		print("==========================================================")
		print("1. Add Subject Record")
		print("2. Search Subject Record")
		print("3. Delete Subject Record")
		print("4. Update Subject Record")
		print("5. Return to Main Menu")
		print("==========================================================")
		choice = int(input("Enter Choice between 1 to 5 ------> : "))
		if choice == 1:
			Subject.insertSubject()
		elif choice == 2:
			Subject.SearchSubject()
		elif choice == 3:
			Subject.deleteSubject()
		elif choice == 4:
			Subject.UpdateSubject()
		elif choice == 5:
			return
		else:
			print("Wrong Choice.....Enter Your Choice again")
			x = input("Enter any key to continue")
Пример #22
0
 def subject(self, name):
     if name not in self._subjects:
         self._subjects[name] = Subject()
     return self._subjects[name]
Пример #23
0
	def makeList(self):
		#make the list of words with radio buttons to go in the scroll window
		if self.dWords:		
			try:
				x = 10 - len(self.Quiz)
			except:
				x = 10
				self.Quiz = []
			if len(self.dWords) >= x:
				myWords = self.dWords[:x]
				del self.dWords[:x]
			else:
				myWords = self.dWords
				del self.dWords[:]
				self.doneButton.SetLabel('Done')

			

			#Quiz will be a list of the button groups that make up a question - which is itself a list
			#each question entry will contain a list containing the label and the radio button options
			
				
			for word in myWords:
				question = []
				wordlabel = wx.StaticText(self.sw, -1, word)
				#wordSizer.Add(wordlabel, 1)
				question.append(wordlabel)
				for a in self.answers:
					id = self.words.index(word) * len(self.answers) + a[0] - 1
					button = wx.CheckBox(self.sw, id, a[1])
					button.SetValue(0)
					#wordSizer.Add(button)
					question.append(button)
				self.Quiz.append(question)
			self.Bind(wx.EVT_CHECKBOX, self.onCheck)		
			try:
				self.mainSizer.Remove(1)
			except:
				pass			
			
			wordSizer = wx.FlexGridSizer(len(self.Quiz), len(self.answers)+1, 10, 10)

			for question in self.Quiz:
				for button in question:
					wordSizer.Add(button)	
			self.mainSizer.Insert(1, wordSizer)			
			return wordSizer, wordSizer.GetMinSize()

		else:
			myloader = Subject.SubLoader()
			sub = myloader.load()
			filename = os.path.join(sub.path, (sub.name + "_memory.pck"))
			textfile = os.path.join(sub.path, (sub.name + "_memory.txt"))
			f = open(filename, 'w')
			pickle.dump(self.answerList, f)
			f.close()
	
			f = open(textfile, 'w')
			for item in self.answerList:
				f.write(str(item) + "\n")
			f.close()
		
			self.Destroy()
Пример #24
0
 def __init__(self):
     app_title()
     self.run = True
     self.subject = Subject()
Пример #25
0
 def __init__(self, kor=0, eng=0, math=0): #디폴트값을 0으로 지정시, 클래스를 불러들일 때 점수를 입력을 하지 않는 상황에서도 실행되게 해줌
    self.seq = 0
    self.title=""
    self.reg_date = ""
    self.__subject = sb.Subject(kor, eng, math)
Пример #26
0
 def __init__(self):
     self.mat = MatFile()
     self.subject = Subject()
     self.signal = SignalUtils()
     self.subject_name = ""
Пример #27
0
class Data:
    def __init__(self):
        self.mat = MatFile()
        self.subject = Subject()
        self.signal = SignalUtils()
        self.subject_name = ""

    def processMat(self, data_file, is_train, contest):
        print(data_file)
        self.mat.readMat(data_file, contest)
        self.mat.name = data_file
        self.mat.sampling_rate = 400
        if contest == 1:
            self.mat.data = self.signal.resample(self.mat.data, 400)
        self.mat.data = self.signal.butterWorthBandpassFilter(self.mat.data,
                                                              band=[0.1, 180],
                                                              frequency=400)
        mat_list = self.mat.getDataList(time_length=self.mat.time_length)
        list_length = mat_list.shape[0]
        sizex, sizey = mat_list[0].data.shape
        matBagX = numpy.zeros((list_length, sizex, sizey))
        matBagY = []

        for i in range(0, list_length):
            matBagX[i, :, :] = mat_list[i].data
            if is_train:
                matBagY.append(self.mat.getMatLabel())
            else:
                matBagY.append(self.mat.name.split("/")[-1])

        return matBagX, matBagY

    def processMatList(self, mat_list, contest, sequence=0, is_train=True):
        dim0 = len(mat_list)
        assert dim0 != 0
        X, Y = self.processMat(mat_list[0], is_train, contest)
        xdim0, xdim1, xdim2 = X.shape
        dim0 = dim0 * xdim0

        data_x = numpy.zeros((dim0, xdim1, xdim2))
        data_y = []
        data_x[0:xdim0, :, :] = X
        data_y += Y

        for i in range(1, len(mat_list)):
            tmp_x, tmp_y = self.processMat(mat_list[i], is_train, contest)
            data_x[i * xdim0:(i + 1) * xdim0, :, :] = tmp_x
            data_y += tmp_y
        if contest == 2:
            data_x = numpy.transpose(data_x, (0, 2, 1))

        return data_x, data_y

    def processSubject(self,
                       subject,
                       is_train,
                       contest,
                       split_number=1,
                       sequence=0):
        data_list = None
        if is_train:
            data_list = self.subject.getTrainFileList(contest=contest,
                                                      name=subject)
        else:
            data_list = self.subject.getTestFileList(contest=contest,
                                                     name=subject)
        if contest == 1:
            if subject.find("Dog") != -1:
                index = subject.find("Dog")
                self.subject_name = subject[index:index + len("Dog") + 2]
            else:
                index = subject.find("Patient")
                self.subject_name = subject[index:index + len("Patient") + 2]
        amount = None
        if len(data_list) % split_number == 0:
            amount = int(len(data_list) / split_number)
        else:
            amount = int(len(data_list) / split_number + 1)
        for i in range(split_number):
            if i == sequence:
                return self.processMatList(data_list[i * amount:(i + 1) *
                                                     amount],
                                           contest=contest,
                                           sequence=sequence,
                                           is_train=is_train)
Пример #28
0
import Observer
import Subject

if __name__ == "__main__":
    weather_data = Subject.WeatherData()
    current_display = Observer.CurrentConditionsDisplay()
    statistics_display = Observer.StatisticsDisplay()
    forecast_display = Observer.ForecastDisplay()

    print('---- Push mode ----')
    weather_data.registerPushObserver(current_display)
    weather_data.registerPushObserver(statistics_display)
    weather_data.registerPushObserver(forecast_display)

    weather_data.simulateChange(80, 65, 30.4)
    weather_data.simulateChange(82, 70, 29.2)
    weather_data.simulateChange(78, 90, 29.2)

    weather_data.removePushObserver(current_display)
    weather_data.removePushObserver(statistics_display)
    weather_data.removePushObserver(forecast_display)
    print('---- Pull mode ----')
    weather_data.registerPullObserver(current_display)
    weather_data.registerPullObserver(statistics_display)
    weather_data.registerPullObserver(forecast_display)

    weather_data.simulateChange(80, 65, 30.4)
    weather_data.simulateChange(82, 70, 29.2)
    weather_data.simulateChange(78, 90, 29.2)

    weather_data.removePullObserver(current_display)
Пример #29
0
def get_subj(num):
    """Returns the subject object associated with num."""
    path = "data/subj" + str(num) + ".json"
    return Subject(path)