예제 #1
0
파일: routes.py 프로젝트: ebkazarina/p
def put_class(name, school_id):
    group = Class(name=name, school_id=school_id)
    db.session.add(group)
    db.session.commit()
    return jsonify(group.json()) if group else ''

    return jsonify(school.json()) if school else ''
예제 #2
0
 def post(self, username=""):
     user = self.getCookieCacheUser()
     class_name = self.request.get("class-name")
     class_instructor = self.request.get("class-instructor")
     class_year = self.request.get("year")
     school_id = self.request.get("school_id")
     school = School.get_by_id(int(school_id))
     if class_name and class_instructor and class_year and school:
         new_class = Class(name=class_name,
                           school=school,
                           instructor=class_instructor,
                           year=int(class_year),
                           user_creator=user,
                           requests=[])
         new_class.other_users.append(str(user.key().id()))
         new_class.put()
         memcache.set(str(user.key().id()) + class_name, new_class)
         memcache.delete(str(user.key().id()))
         self.redirect("/%s/%s" % (user.username, new_class.name))
     else:
         schools = School.all()
         self.render("create-class.html",
                     schools=schools,
                     class_name=class_name,
                     class_instructor=class_instructor,
                     year=class_year,
                     class_active="active")
예제 #3
0
def AddClass(request):
    if request.method == 'POST':
        form = AddNameForm(request.POST)
        if form.is_valid():
            user = request.user
            if user.is_authenticated() and IsHead(user):
                head = StudyHead.objects.get(ForUser=user)
                cls = Class(ForHead=head, Name=form.cleaned_data['Name'])
                cls.save()

    return HttpResponseRedirect("/accounts/")
예제 #4
0
파일: views.py 프로젝트: adideshp/Tutor
def create_class(request):
    #import pdb; pdb.set_trace()
    result_obj = json.loads(request.body)
    user_profile = User_Profile.objects.filter(user = request.user)
    new_class = Class()
    new_class.name = result_obj['name']
    new_class.instructor = user_profile[0]
    new_class.save()
    add_students_in_class(result_obj, new_class.id)
    return_obj = {"class_id" : new_class.id}
    return JsonResponse(return_obj)
예제 #5
0
 def createClassAndStudents(self):
   c = Class()
   c.name = 'Test Class'
   self.class_key = c.put()
   c = self.class_key.get()
   self.timezone = c.timezone
   s = Student()
   s.first_name = 'Joe'
   s.last_name = 'Smith'
   self.student_key = s.put()
   c.enrolled.append(self.student_key)
   c.put()
   # TODO: fix this to use a known date, since could potentially have problems if run in different timezone to default
   self.today_as_ordinal = Attend.today_as_ordinal(self.timezone)
예제 #6
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
    def groups(self, *args, **kwargs):
        self.stdout.write("Populating classes table")

        programs = [
            "B.Ed. (Arts)",
            "B.Ed. (Social Science)",
            "B.Ed. (Social Studies)",
            "B.Ed. (Accounting)",
            "B.Ed. (Management)",
            "B.Ed. (Science),",
            "B.Ed. (Mathematics)",
            "B.Ed. (Computer Science)",
            "B.Ed. (Health Science)",
            "B.Ed. (Health, Physical Education & Recreation)",
            "B.Ed. (Home Economics)",
            "B.Sc. (Computer Science)",
            "B.Sc. (Engineering Physics)",
            "B.Sc. (Industrial Chemistry)",
            "B.Sc. (Information Technology)",
            "B.Sc. (Laboratory Technology)",
            "B.Sc. (Mathematics)",
        ]
        levels = [1, 2, 3, 4]

        for p in programs:
            now = datetime.now()
            start = date(now.year - random.choice(levels), 8, 21)
            end = date(start.year + 4, 8, 21)
            Class(
                program=p,
                size=random.randint(50, 150),
                admission_year=start,
                completion_year=end,
            ).save()
예제 #8
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete
    _multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
예제 #9
0
 def DeleteClass(self, *args):
     from google.appengine.ext import db
     from models import Task, Class, Book, Chapter
     from google.appengine.api import users
     user = users.get_current_user()
     classname = args[0].replace('%20', ' ')
     #Deleting all Tasks for this Module
     q = Task.all().filter('user ==',user).filter('classname ==',classname)
     results = q.fetch(10)
     for result in results:
         result.delete()
     #Deleting all the Scripts and Chapters from this Module
     qq = Book.all().filter('user ==',user).filter('classname ==',classname)
     books = qq.fetch(10)
     for book in books:
         qqq = Chapter.all().filter('book ==', book.title).filter('user ==',user)
         for chapter in qqq:
             chapter.delete()
         book.delete()
     #Deleting the Module itself
     qqqq = Class.all().filter('user ==',user).filter('name ==',classname)
     results = qqqq.fetch(10)
     for result in results:
         result.delete()
     return self.RefreshClasses()
def add_class_to_db():
    class_list = ['Пятый', 'Шестой', 'Седьмой', 'Восьмой', 'Девятый']
    for i in class_list:
        to_db = Class(i)
        db.session.add(to_db)

    db.session.commit()
예제 #11
0
def create_class():
    class_name = request.form.get('class_name')
    deadline = request.form.get('deadline')
    groups = json.loads(request.form.get('groupJSON'))
    class_create = Class(class_name, deadline)

    print(class_name, deadline, groups)
    db.session.add(class_create)
    db.session.commit()

    for i, g in enumerate(groups):
        group_password = ''.join(
            random.choice(string.ascii_uppercase + string.digits)
            for _ in range(8))
        password_hash = bcrypt.generate_password_hash(group_password)
        group = Group(username=g['username'],
                      password_hash=password_hash,
                      members=g['members'],
                      class_id=class_create.id)
        groups[i]['password'] = group_password

        db.session.add(group)

    db.session.commit()

    mailer.send_passwords(groups)

    response = dict()

    response['success'] = True
    response['message'] = "Successfully created class " + class_name + "!"

    return jsonify(response)
예제 #12
0
def classRegistration():

    if(session['logged_in']): #if user not loggin
        if(request.method == 'GET'):
            return render_template('classRegistration.html')

        elif(request.method == 'POST'):
            try:
                t_id = request.json['t_id']
                class_id = request.json['class_id']
                grade = request.json['grade']
                subject = request.json['subject']

                teacher = DataPipelineObj.get_teacher_details(t_id)

                if(teacher):                           #if there is a teacher with that id
                    newClass = Class(class_id, grade, subject)
                    new_teacher_class = Teacher_class(t_id, class_id)
                    DataPipelineObj.insert_data(newClass)            #add new class etails into the database
                    DataPipelineObj.insert_data(new_teacher_class)
                    return jsonify({'status':"Class successfully registered"}) #update teache_class table

                else:                                                #if there is not a teacher with that id
                    return jsonify({'status':"There is no such teacher id"})
            except:
                 return jsonify({'status':"There is something wrong. Check whether you have filled require details correctly"})

    else: #if user not login
        return render_template('showSignIn.html')
예제 #13
0
def populate_classes():
    klass = Class(refno='MTID101',
                  th_class_name=u'การเรียนรู้เพื่อการเปลี่ยงแปลงสำหรับ MT',
                  en_class_name='Transformative learning for MT',
                  academic_year='2560')
    db.session.add(klass)
    db.session.commit()
예제 #14
0
 def AddTask(self, *args):
     from datetime import date
     from models import Class
     user = users.get_current_user()
     classes = Class.all().order("exam").filter('user ==',user).filter('exam >', date.today())
     path = os.path.join(os.path.dirname(__file__), "templates","addtask.html")
     template_values = { 'classes': classes }
     code = template.render(path, template_values).decode('utf-8')
     return code
예제 #15
0
 def cacheClass(self, user_key, class_name):
     class_obj = memcache.get(str(user_key) + class_name)
     if type(class_obj) is Class:
         return class_obj
     else:
         class_obj = Class.all().filter('name =', class_name).filter(
             'other_users ==', str(user_key)).get()
         memcache.set(str(user_key) + class_name, class_obj)
         return class_obj
예제 #16
0
파일: main.py 프로젝트: Logiraptor/cmps453
	def get(self):
		students = list(Student.query())
		for s in students:
			s._teacher = s.teacher.get()
			s.teacher_name = s._teacher.name

		teachers = {s._teacher.name:s._teacher for s in students}

		classes = []
		for teacher_name, teacher in teachers.items():
			c = Class()
			c.teacher = teacher
			c.students = filter(lambda s: s.teacher_name == teacher_name, students)
			classes.append(c)
		self.render('html/view_all.html', {
			'errors':[],
			'classes': classes,
		})
예제 #17
0
 def get(self):
     user = self.getCookieCacheUser()
     if user:
         the_classes = Class.all().filter("user_creator !=", user)
         user_classes = self.cacheAllUserClasses(user.key().id())
         page_title = "Welcome " + user.username
         self.render('index.html',
                     current_user=user,
                     the_classes=the_classes,
                     page_title=page_title,
                     user_classes=user_classes)
     else:
         the_classes = Class.all()
         page_title = "Welcome To Sparquiz"
         self.render('index.html',
                     current_user=None,
                     the_classes=the_classes,
                     page_title=page_title)
예제 #18
0
 def cacheAllUserClasses(self, user_key):
     all_user_classes = memcache.get(str(user_key) + "all")
     if type(all_user_classes) is list:
         return all_user_classes
     else:
         all_user_classes = Class.all().filter(
             'other_users ==', str(user_key)).order("last_updated")
         memcache.set(str(user_key) + "all", all_user_classes)
         return all_user_classes
예제 #19
0
def newClass():
    form = ClassForm()
    if form.validate_on_submit():
        name = form.name.data
        describe = form.describe.data
        post = Class(name=name, describe=describe, user_id=current_user.id)
        db.session.add(post)
        db.session.commit()
        flash('Post success')
        return redirect(url_for('index'))
    return render_template('newClass.html', form=form)
예제 #20
0
파일: classes.py 프로젝트: shubashri/src
    def handleGetRequest(self):
        # get the recent 10 classes added to datastore
        q = Class.query(ancestor=CLASS_KEY)
        classes = q.order(-Class.created).fetch(20)

        # get the recent 10 class-categories added to datastore
        q = ClassCategory.query(ancestor=CLASS_CATEGORY_KEY)
        categories = q.order(-ClassCategory.created).fetch(20)

        self.addTemplateValue('classes', classes)
        self.addTemplateValue('categories', categories)

        self.setActivePage('Classes')
예제 #21
0
 def RefreshClasses(self):
     from models import Class, Task, Book
     from datetime import date
     user = users.get_current_user()
     books = Book.all().filter('user ==',user)
     classes = Class.all().order("exam").filter('user ==',user).filter('exam >', date.today())
     template_values = {
                        'books' : books,
                        'classes': classes
                        }
     path = os.path.join(os.path.dirname(__file__), "templates", "listmoduls.html")
     code = template.render(path, template_values).decode('utf-8')
     return code
예제 #22
0
 def get(self):
   user = users.get_current_user()
   namespace_manager.set_namespace('')
   students = ['John Lennon',
               'Ringo Starr',
               'George Harrison',
               'Paul McCartney',]
   student_list = []
   for name in students:
     first_name, last_name = name.split()
     student = Student(first_name=first_name, last_name=last_name)
     student_key = student.put()
     student_list.append(student_key)
   music = Class(name='Music 101', enrolled=student_list)
   music.put()
   students = ['David Beckham',
               'Lionel Messi',
               'Diego Maradonna',
               'Cristiano Ronaldo',
               'George Best',
               'Wayne Rooney',
               'Zinedine Zidane',]
   student_list = []
   for name in students:
     first_name, last_name = name.split()
     student = Student(first_name=first_name, last_name=last_name)
     student_key = student.put()
     student_list.append(student_key)
   soccer = Class(name='Soccer camp', enrolled=student_list)
   soccer.put()
   students = ['Darth Vader',
               'Gordon Gekko',
               'Auric Goldfinger',
               'Count Dracula', ]
   student_list = []
   for name in students:
     first_name, last_name = name.split()
     student = Student(first_name=first_name, last_name=last_name)
     student_key = student.put()
     student_list.append(student_key)
   detention = Class(name='Detention', enrolled=student_list, default_hours=2)
   detention.put()
   self.response.out.write('done')
예제 #23
0
def migrate_classes():
    df = pd.read_csv(os.path.join(path, "data/courses.csv"))
    for index, row in tqdm(df.iterrows(), total=len(df.index)):
        new_course = {n: row[conversion_dict[n]] for n in conversion_dict}
        course = Class.query.filter_by(term=row["Associated Term"],
                                       crn=row["CRN"]).first()
        if course and not all(
            [course.__dict__[n] == new_course[n] for n in new_course]):
            continue
        if course:
            course.data = new_course
        else:
            course = Class(**new_course)
            db.session.add(course)
        db.session.commit()
예제 #24
0
def new_class(request):
    if request.method == 'POST':
        form = NewClassForm(request.POST)
        if form.is_valid():
            pkgs = re.findall(r'[^,;\s]+', form.cleaned_data['packages'])
            new_class = Class(teacher = Teacher.objects.get(user=request.user),
                              name = form.cleaned_data['name'],
                              class_size = form.cleaned_data['class_size'],
                              droplet_image = form.cleaned_data['droplet_image'],
                              droplet_size = form.cleaned_data['droplet_size'],
                              droplet_region = form.cleaned_data['droplet_region'],
                              packages=' '.join(pkgs))
                              # droplet_priv_net = form.cleaned_data['droplet_priv_net'],
                              # droplet_ipv6 = form.cleaned_data['droplet_ipv6'])
            new_class.save()
            launch_droplets(request, new_class)
            return redirect('/class/' + new_class.prefix)
        else:
            return HttpResponse(form.errors)
    else:
        form = NewClassForm()
        teacher = Teacher.objects.get(user=request.user)
        return render(request, 'new_class.html',
                     {'form': form, 'acct': teacher})
예제 #25
0
 def get(self, username=""):
     user = self.getCookieCacheUser()
     if user:
         if user.username == username:
             classes = Class.all().filter(
                 "other_users ==",
                 str(user.key().id())).order("last_updated")
             page_title = "List of Classes"
             self.render('edituserprofile.html',
                         page_title=page_title,
                         current_user=user,
                         classes=classes,
                         class_active="active")
     else:
         user_profile = self.get_user_by_name(username)
         self.render('userprofile.html', user_profile=user_profile)
예제 #26
0
def create_class(request):
    #import pdb; pdb.set_trace()
    result_obj = json.loads(request.body)
    user_profile = User_Profile.objects.filter(user=request.user)
    new_class = Class()
    new_class.name = result_obj['name']
    new_class.instructor = user_profile[0]
    new_class.save()
    add_students_in_class(result_obj, new_class.id)
    return_obj = {"class_id": new_class.id}
    return JsonResponse(return_obj)
예제 #27
0
 def testAttendAddFirstStudent(self):
   params = {'class_id': self.class_key.id(), 
             'student_id': self.student_key.id(), 
             'yes': 1, 'date': self.today_as_ordinal}
   response = self.testapp.get('/attend', params)
   self.assertEqual(response.status_int, 302)
   query = Class.query()
   results = query.fetch(2)
   self.assertEqual(1, len(results))
   self.assertEqual('Test Class', results[0].name)
   attendance_key = ndb.Key('Class', self.class_key.id(), 'Attendance', self.today_as_ordinal)
   attendance = attendance_key.get()
   self.assertEqual(1, len(attendance.attending))
   student_key = attendance.attending[0].student
   student = student_key.get()
   self.assertEqual('Joe', student.first_name)
   self.assertEqual('Smith', student.last_name)
예제 #28
0
    def get(self):
        #imports
        from models import Class, Task, Book
        from datetime import date
        
        #get current User
        user = users.get_current_user()
        
        #Check if user wants to change the language
        cookie_django_language = self.request.get('language', '')
        if cookie_django_language:
            if cookie_django_language == 'unset':
                del self.request.COOKIES['django_language']
            else:
                self.request.COOKIES['django_language'] = cookie_django_language
            self.reset_language()

        if user:
            classes = Class.all().order("exam").filter('user ==',user).filter('exam >', date.today())
            logoutlink = users.create_logout_url(self.request.uri)
            books = Book.all().filter('user ==',user)
            inline = Task.all().order("enddate").filter('state ==','Offen').filter('user ==',user).filter('enddate >', date.today())
            urgent = Task.all().order("enddate").filter('state ==','Offen').filter('user ==',user).filter('enddate <=', date.today())
            template_values = {
                           'books' : books,
                           'title':'Task Management',
                           'user' : user.email(),
                           'tasks': inline,
                           'urgent': urgent,
                           'logout' : logoutlink,
                           'classes': classes
                           }
            path = os.path.join(os.path.dirname(__file__), 'templates', "index.html")
            self.response.out.write(template.render(path, template_values).decode('utf-8'))
        else:
            providers = []
            for p in openIdProviders:
                p_name = p.split('.')[0].lower()
                p_url = p.lower()
                providers.append([users.create_login_url(federated_identity=p_url), p_name])
            template_values = { 
                           'providers' : providers,
            }
            path = os.path.join(os.path.dirname(__file__), 'templates', "login.html")
            self.response.out.write(template.render(path, template_values).decode('utf-8'))
예제 #29
0
 def get(self):
   authz = Authorize()
   if not authz.authorize():
     self.error(403)
     return
   query = Class.query()
   # Max classes that can be handled is 50 per school
   classes = query.fetch(50)
   for the_class in classes:
     the_class.id = the_class.key.id()
   school = namespace_manager.google_apps_namespace()
   if not school: school = 'Test school'
   template_values = { 'classes': classes,
                       'school': school,
                       'username': authz.get_name(),
                       'logout': users.create_logout_url("/") }
   path = os.path.join(os.path.dirname(__file__), 'templates/classes.html')
   self.response.out.write(template.render(path, template_values))
예제 #30
0
 def post(self, username="", class_name=""):
     user = self.getCookieCacheUser()
     user_creator = self.get_user_by_name(username)
     class_obj = Class.all().filter('name =', class_name).filter(
         'user_creator =', user_creator).get()
     if user and user_creator and class_obj:
         if str(user.key().id()) not in class_obj.requests and str(
                 user.key().id()) not in class_obj.other_users:
             class_obj.requests.append(str(user.key().id()))
             class_obj.put()
             memcache.delete(str(user_creator.key().id()) + class_name)
             my_response = {'msg': 'success'}
             json_response = json.dumps(my_response)
             self.response.headers.add_header('content-type',
                                              'text/json',
                                              charset='utf-8')
             self.response.out.write(json_response)
     else:
         self.write("We cannot process your request")
def get_courses(year, semester):
    print("Downloading course list")
    s.get("http://yjs.ustc.edu.cn/course/query.asp?mode=dept")
    r = s.post(
        "http://yjs.ustc.edu.cn/course/m_querybyname.asp",
        data="year1=" + year + "&term1=" + semester +
        "&querykc=_&submit=%B2%E9+%D1%AF",
        headers={"Content-Type": "application/x-www-form-urlencoded"},
    )
    soup = BeautifulSoup(r.content, "html5lib")
    courses = []
    for row in soup.find_all("table")[3].find_all("tr")[1:]:
        cols = row.find_all("td")
        cno = cols[0].text
        name = cols[1].text
        teacher = cols[2].text
        week = cols[3].text
        selected = int(cols[5].text)
        list_params = ([cols[5].a["href"].split("'")[i]
                        for i in (1, 3, 5)] if selected else None)
        limit = int(cols[6].text)
        classes = []
        for c in cols[4].text.split(";"):
            parts = c.rsplit(": ", 1)
            if len(parts) == 1:
                location, time = "", parts[0]
            else:
                location, time = parts
            classes.append(Class(location, time))
        courses.append(
            Course(cno, name, teacher, week, classes, selected, limit, None,
                   list_params))
    for i, course in enumerate(courses):
        print("[%s/%s] %s %s" % (i + 1, len(courses), course.cno, course.name))
        if course.selected:
            course.students = get_students(*course.list_params)
        else:
            course.students = []
    return courses
예제 #32
0
def editClass():
    if request.method == "POST":
        class_name = request.form["class_name"]
        dept = request.form["dept"]
        number = request.form["number"]
        desc = request.form["desc"]
        new_class = Class(class_name, dept, number, desc)
        db_session.add(new_class)
        db_session.commit()
        data = {
            "id": new_class.id,
            "class_name": class_name,
            "dept": dept,
            "number": number,
            "desc": desc
        }

        pusher_client.trigger('table', 'new-class', {'data': data})

        return redirect("/editClass", code=302)
    else:
        classes = Class.query.all()
        return render_template('edit-class.html', classes=classes)
예제 #33
0
async def get(id: int):
    return await ClassBaseOut.from_queryset_single(Class.get(id=id))
예제 #34
0
def get_class(class_name):
  qry = Class.query().filter(Class.name == class_name)
  return qry.fetch(1)
예제 #35
0
파일: app.py 프로젝트: ebkazarina/p
from flask import Flask
from models import db, School, Class, Student, Teacher
from routes import classesApi, schoolsApi, teachersApi, studentsApi, index

app = Flask(__name__)
app.register_blueprint(classesApi)
app.register_blueprint(schoolsApi)
app.register_blueprint(teachersApi)
app.register_blueprint(studentsApi)
app.register_blueprint(index)
db.init_app(app)

with app.app_context():
    db.create_all()
    school = School(name='middle50', address='address')
    db.session.add(school)
    db.session.commit()
    group = Class(name='1A', school_id=school.id)
    db.session.add(group)
    db.session.commit()
    db.session.add(Student(name='Vasya', class_id=group.id))
    db.session.add(Teacher(name='Irina', class_id=group.id, subject='Math'))
    db.session.commit()
if __name__ == "__main__":
    app.run()
예제 #36
0
 def save(self, commit=True):
     newclass = Class(classid=self.cleaned_data['classid'],
                      classname=self.cleaned_data['classname'])
     if commit:
         newclass.save()
     return newclass
예제 #37
0
    def get(self):

        # CLEAR All
        query = Department.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = House.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Class.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Student.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        user = users.get_current_user()
        if user and users.is_current_user_admin():
            # Create houses
            houses = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']
            for house in houses:
                House(house_name=house).put()

            # Create departments
            deps = [
                {
                    'code': 'CS',
                    'name': 'Computer Science'
                },
                {
                    'code': 'BA',
                    'name': 'Business Administration'
                },
                {
                    'code': 'PHY',
                    'name': 'Physics'
                },
                {
                    'code': 'MAT',
                    'name': 'Mathematics'
                },
                {
                    'code': 'DRA',
                    'name': 'Drama'
                },
                {
                    'code': 'ECE',
                    'name': 'Electrical Engineering'
                },
            ]
            for dep in deps:
                Department(id=dep['code'], dept_name=dep['name']).put()

            # Create 40 classes for department, update depts
            classes_count = 40
            for dept in deps:
                department_key = ndb.Key('Department', dept['code'])
                department_obj = department_key.get()
                for i in range(classes_count):
                    class_full_name = "%s - Class %d" % (dept['name'], i)
                    department = department_key
                    class_key = Class(id='%s-%d' % (dept['code'], i),
                                      class_full_name=class_full_name).put()
                    department_obj.classes.append(class_key)
                department_obj.put()

            # Create students
            students_count = 1000
            random.seed()
            all_classes = Class.query().fetch()
            all_houses = House.query().fetch()
            for i in range(students_count):
                house = random.choice(all_houses)
                house_key = house.key
                student_name = 'Student %d' % i
                student_year = random.randint(1, 4)
                current_classes = random.sample(all_classes, 5)
                current_classes_keys = [el.key for el in current_classes]
                all_classes_keys = [el.key for el in all_classes]
                leftovers = set(all_classes_keys) - set(current_classes_keys)
                completed_classes_keys = random.sample(leftovers,
                                                       6 * (student_year - 1))
                student_key = Student(student_name=student_name,
                                      student_year=student_year,
                                      current_classes=current_classes_keys,
                                      completed_classes=completed_classes_keys,
                                      house=house_key).put()
                house.students.append(student_key)
                for el in current_classes:
                    el.students_enrolled.append(student_key)
            # save new status of houses and current classes
            for house in all_houses:
                house.put()
            for current_class in all_classes:
                current_class.put()

        elif user and not users.is_current_user_admin():
            self.redirect(users.create_logout_url('/create_entries'))
        else:
            self.redirect(users.create_login_url('/create_entries'))
예제 #38
0
    def post(self):
        from datetime import datetime, date
        from models import Task, Book, Class
        user = users.get_current_user()
        from cgi import escape
        
        type = escape(self.request.get('type'))
        
        if type == 'task':
            if self.request.get('description'):
                beschreibung = self.request.get('description')
            else:
                beschreibung = _("Keine Beschreibung vorhanden")
            classname = escape(self.request.get('class'))
            if classname == "":
                color = 'gray'
                classname = 'None'
            else:
                colors = Class.all().filter('user ==',user).filter('name ==',self.request.get('class'))
                for c in colors:
                    color = c.color
            if self.request.get('homework') == "checked":
                home = True
            else:
                home = False
            try:
                enddate = datetime.strptime(self.request.get('enddate'),"%d.%m.%Y %H:%M")
            except:
                try:
                    enddate = datetime.strptime(self.request.get('enddate'),"%d.%m.%Y")
                except:
                    enddate = datetime.strptime("1.1.1970","%d.%m.%Y")

            entry = Task( 
                title = escape(self.request.get('name').replace('/','-')),
                classname = classname,
                color = color,
                homework = home,
                state = "Offen",
                user = user,
                text = beschreibung,
                enddate = enddate
            )
            entry.put()
            self.redirect('/')
        if type == 'class':
            if escape(self.request.get('preexam')) == "checked":
                preexam = True
            else:
                preexam = False
            try:
                examdate = datetime.strptime(escape(self.request.get('exam')),"%d.%m.%Y")
            except:
                try:
                    examdate = datetime.strptime(escape(self.request.get('exam')),"%d.%m.%Y %H:%M")
                except:
                    self.redirect('/')
                #better solution needed!
            entry = Class( 
                name = escape(self.request.get('name')),
                color = escape(self.request.get('color')),
                semester = int(escape(self.request.get('semester'))),
                preexam = preexam,
                user = user,
                exam = examdate
            )
            entry.put()
            self.redirect('/')
        if type == 'book':
            import re
            from models import Book, Chapter
            skentry = Book(
                            title = self.request.get('name'),
                            classname = self.request.get('class'),
                            user = user
                           )
            skentry.put()
            index = escape(self.request.get('index'))
            pfound = re.compile('(\d*(\.\d*)*)\s(.+?)(\.{2,}|\s|(\.\s)+)(\d+)')
            for line in index.split('\n'):
                found = pfound.search(line)
                try:
                    name = found.group(3)
                    number = found.group(1)
                    entry = Chapter(
                                title = name,
                                number = number,
                                user = user,
                                book = self.request.get('name'),
                                state = "offen"
                                )
                    entry.put()
                except:
                    pass
            self.redirect('/')
        self.redirect('/')
예제 #39
0
from models import Class, Data

C1 = [(200, 160, 120), (210, 170, 130), (215, 172, 133), (210, 165, 134),
      (198, 177, 138)]
C2 = [(90, 130, 60), (92, 138, 54), (87, 128, 66), (91, 134, 60),
      (85, 123, 55)]
C3 = [(30, 44, 178), (20, 40, 180), (24, 42, 184), (28, 50, 176),
      (22, 46, 181)]
color_classes = [C1, C2, C3]
classes = []
i = 1

for c in color_classes:
    items = []
    helper = Class(name="c" + str(i))
    for item in c:
        items.append(
            Data(name="",
                 characteristics={
                     "r": item[0],
                     'b': item[1],
                     'g': item[2]
                 }))
    helper.load_items(items)
    i += 1
    classes.append(helper)
예제 #40
0
def parse_taxonomy(Document):
    f = csv.reader(Document, delimiter='\t')
    f.next()

    for line in f:
        subbed = re.sub(r'(\(.*?\)|k__|p__|c__|o__|f__|g__|s__)', '', line[2])
        taxon = subbed.split(';')

        if not Kingdom.objects.filter(kingdomName=taxon[0]).exists():
            kid = uuid4().hex
            record = Kingdom(kingdomid=kid, kingdomName=taxon[0])
            record.save()
        k = Kingdom.objects.get(kingdomName=taxon[0]).kingdomid

        if not Phyla.objects.filter(kingdomid_id=k,
                                    phylaName=taxon[1]).exists():
            pid = uuid4().hex
            record = Phyla(kingdomid_id=k, phylaid=pid, phylaName=taxon[1])
            record.save()
        p = Phyla.objects.get(kingdomid_id=k, phylaName=taxon[1]).phylaid

        if not Class.objects.filter(
                kingdomid_id=k, phylaid_id=p, className=taxon[2]).exists():
            cid = uuid4().hex
            record = Class(kingdomid_id=k,
                           phylaid_id=p,
                           classid=cid,
                           className=taxon[2])
            record.save()
        c = Class.objects.get(kingdomid_id=k, phylaid_id=p,
                              className=taxon[2]).classid

        if not Order.objects.filter(
                kingdomid_id=k, phylaid_id=p, classid_id=c,
                orderName=taxon[3]).exists():
            oid = uuid4().hex
            record = Order(kingdomid_id=k,
                           phylaid_id=p,
                           classid_id=c,
                           orderid=oid,
                           orderName=taxon[3])
            record.save()
        o = Order.objects.get(kingdomid_id=k,
                              phylaid_id=p,
                              classid_id=c,
                              orderName=taxon[3]).orderid

        if not Family.objects.filter(kingdomid_id=k,
                                     phylaid_id=p,
                                     classid_id=c,
                                     orderid_id=o,
                                     familyName=taxon[4]).exists():
            fid = uuid4().hex
            record = Family(kingdomid_id=k,
                            phylaid_id=p,
                            classid_id=c,
                            orderid_id=o,
                            familyid=fid,
                            familyName=taxon[4])
            record.save()
        f = Family.objects.get(kingdomid_id=k,
                               phylaid_id=p,
                               classid_id=c,
                               orderid_id=o,
                               familyName=taxon[4]).familyid

        if not Genus.objects.filter(kingdomid_id=k,
                                    phylaid_id=p,
                                    classid_id=c,
                                    orderid_id=o,
                                    familyid_id=f,
                                    genusName=taxon[5]).exists():
            gid = uuid4().hex
            record = Genus(kingdomid_id=k,
                           phylaid_id=p,
                           classid_id=c,
                           orderid_id=o,
                           familyid_id=f,
                           genusid=gid,
                           genusName=taxon[5])
            record.save()
        g = Genus.objects.get(kingdomid_id=k,
                              phylaid_id=p,
                              classid_id=c,
                              orderid_id=o,
                              familyid_id=f,
                              genusName=taxon[5]).genusid

        if not Species.objects.filter(kingdomid_id=k,
                                      phylaid_id=p,
                                      classid_id=c,
                                      orderid_id=o,
                                      familyid_id=f,
                                      genusid_id=g,
                                      speciesName=taxon[6]).exists():
            sid = uuid4().hex
            record = Species(kingdomid_id=k,
                             phylaid_id=p,
                             classid_id=c,
                             orderid_id=o,
                             familyid_id=f,
                             genusid_id=g,
                             speciesid=sid,
                             speciesName=taxon[6])
            record.save()
예제 #41
0
def get_classes_file(clases_file):
    if not os.path.isfile(clases_file):
        fp = open(clases_file, "w")
        fp.writelines("\n".join(["M", "N"]))
        print " * %s created" % classes_txt
        print "   go and modify meet classes"
        sys.exit(1)
    else:
        return open(classes_txt)


if __name__ == "__main__":

    # read confg
    conf = get_config()

    # get engine
    engine = create_engine(conf["DATABASE_URI"], echo=True)
    from sqlalchemy.orm import sessionmaker
    db_session = sessionmaker(bind=engine)()

    classes_txt = "classes.txt"
    classes = get_classes_file(classes_txt)

    print " * Creating classses form: %s" % classes_txt
    for line in classes:
        class_name = line.strip()
        db_session.add(Class(name=class_name))

    db_session.commit()
예제 #42
0
    def parse_line(self, line):
        columns = line.split(self.HAZARDS_DELIMITER)

        # Check columns count
        if len(columns) != self.HAZARDS_COL_COUNT:
            self.error = 'Number of columns must be %d' % self.HAZARDS_COL_COUNT
            return False

        # Clean columns
        temp = []
        for col in columns:
            temp.append(col.strip())
        columns = temp

        # Check signal word
        if not HStatement.is_signal_word(columns[self.HAZARDS_COL_SIGNALWORD]):
            self.error = "'%s' is not a signal word!" % columns[
                self.HAZARDS_COL_SIGNALWORD]
            return False

        pictogram_names = columns[self.HAZARDS_COL_PICTOGRAM].strip()
        for pic_name in pictogram_names.split(','):
            pic_name = pic_name.strip()
            image_name = pic_name + self.HAZARDS_PICTOGRAM_TYPE
            image = None
            try:
                image = self.zip_file.read(image_name)
            except KeyError:
                self.error = 'Did not find <b>%s</b> in zip-file.' % image_name
                return False
            else:
                # Parse Pictogram
                pic = Pictogram.load(pic_name, image)

                # Parse H-Statement
                hstatement = HStatement.load(columns[self.HAZARDS_COL_CODE])
                hstatement.statement = columns[self.HAZARDS_COL_HSTATEMENT]
                hstatement.set_signal_word(
                    columns[self.HAZARDS_COL_SIGNALWORD])

                # Parse Class
                cls = Class.laod(columns[self.HAZARDS_COL_CLASS])
                cls.pictogram = pic.key

                # Parse Category (can be a list)
                cats = self.parse_category(columns[self.HAZARDS_COL_CATEGORY])
                if cats:
                    for cat in cats:
                        c = Classification(parent=CLASSIFICATION_KEY,
                                           clazz=cls.key,
                                           category=cat.key,
                                           hstatement=hstatement.key)
                        c.put()
                        cat.put()
                else:
                    self.error = "Category '%s' could not be understood." % columns[
                        self.HAZARDS_COL_CATEGORY]
                    return False

                # Store all the entities now where everything is fine
                pic.put()
                hstatement.put()
                cls.put()

        return True
예제 #43
0
파일: forms.py 프로젝트: andyzsf/ERP_Django
 def save(self,commit=True):
     newclass = Class(classid=self.cleaned_data['classid'],classname=self.cleaned_data['classname'])
     if commit:
         newclass.save()
     return newclass
from django.utils import crypto

from models import Game, Entity, ItemDefinition, Item, Class, Power, Character, Credential, Account, Subscription

rkit.connect("localhost", int(sys.argv[1]) if len(sys.argv) > 1 else 8081)
print "Making test models..."

precursors = Game()
precursors.pk = "precursors"
precursors.name = "Requiem for Innocence: Precursors"
precursors.save()

print "Finished Game."


soldier = Class()
soldier.game = precursors
soldier.name = "Soldier"
soldier.primary_stat = "strength"
soldier.save()

operative = Class()
operative.game = precursors
operative.name = "Operative"
operative.primary_stat = "dexterity"
operative.save()

officer = Class()
officer.game = precursors
officer.name = "Officer"
officer.primary_stat = "charisma"
예제 #45
0
	errorMsg='无法在%s %s找到%s,%s' % (out['province'],out['city'],out['district'],e)
	return InvalidUrl(errorMsg)

    #检查是否是学校管理员电话 
    try:
	sa = SchoolAdministrator.objects.get(telephone = out[telephone])
    except DoesNotExist,e:
	errorMsg='the current user is not a school administrator,only school administrators can create school'
	return InvalidUrl(errorMsg)

    try:
	school = district.school_set.get(school__name = out['school_name'])
    except DoesNotExist,e:
	errorMsg='can not find school %s in district %s' % (out['school_name'],out['district'])
	return InvalidUrl(errorMsg)
    school_class = Class(name = out['name'])
    school_class.save() 
    school.add(school_class)
    school.save()	
    result = '成功创建班级:%s 学校:%s 学校负责人:%s' % (out['name'],out['school_name'],sa.name)
    return RightResponse(result)

def updateClass(request):
    pass

def queryClass(request):
    pass

def deleteClass(request):
    pass
예제 #46
0
    def get(self):

        # CLEAR All
        query = Department.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = House.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Class.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Student.query()
        entries = query.fetch()
        entry_keys = [entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        user = users.get_current_user()
        if user and users.is_current_user_admin():
            # Create houses
            houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]
            for house in houses:
                House(house_name=house).put()

            # Create departments
            deps = [
                {"code": "CS", "name": "Computer Science"},
                {"code": "BA", "name": "Business Administration"},
                {"code": "PHY", "name": "Physics"},
                {"code": "MAT", "name": "Mathematics"},
                {"code": "DRA", "name": "Drama"},
                {"code": "ECE", "name": "Electrical Engineering"},
            ]
            for dep in deps:
                Department(id=dep["code"], dept_name=dep["name"]).put()

            # Create 40 classes for department, update depts
            classes_count = 40
            for dept in deps:
                department_key = ndb.Key("Department", dept["code"])
                department_obj = department_key.get()
                for i in range(classes_count):
                    class_full_name = "%s - Class %d" % (dept["name"], i)
                    department = department_key
                    class_key = Class(id="%s-%d" % (dept["code"], i), class_full_name=class_full_name).put()
                    department_obj.classes.append(class_key)
                department_obj.put()

            # Create students
            students_count = 1000
            random.seed()
            all_classes = Class.query().fetch()
            all_houses = House.query().fetch()
            for i in range(students_count):
                house = random.choice(all_houses)
                house_key = house.key
                student_name = "Student %d" % i
                student_year = random.randint(1, 4)
                current_classes = random.sample(all_classes, 5)
                current_classes_keys = [el.key for el in current_classes]
                all_classes_keys = [el.key for el in all_classes]
                leftovers = set(all_classes_keys) - set(current_classes_keys)
                completed_classes_keys = random.sample(leftovers, 6 * (student_year - 1))
                student_key = Student(
                    student_name=student_name,
                    student_year=student_year,
                    current_classes=current_classes_keys,
                    completed_classes=completed_classes_keys,
                    house=house_key,
                ).put()
                house.students.append(student_key)
                for el in current_classes:
                    el.students_enrolled.append(student_key)
            # save new status of houses and current classes
            for house in all_houses:
                house.put()
            for current_class in all_classes:
                current_class.put()

        elif user and not users.is_current_user_admin():
            self.redirect(users.create_logout_url("/create_entries"))
        else:
            self.redirect(users.create_login_url("/create_entries"))
예제 #47
0
def add_class(class_name):
  c = Class(name=class_name)
  k = c.put()
  return k
예제 #48
0
async def read(current_user: User = Depends(getTokenUser)):
    classes = Class.all().select_related("level", "section", "a_s")
    return await ClassBaseOut.from_queryset(classes)
예제 #49
0
    def get(self):

        # CLEAR All
        query = Department.query()
        entries =query.fetch()
        entry_keys =[entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = House.query()
        entries =query.fetch()
        entry_keys =[entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Class.query()
        entries =query.fetch()
        entry_keys =[entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        query = Student.query()
        entries =query.fetch()
        entry_keys =[entry.key for entry in entries]
        ndb.delete_multi(entry_keys)

        user = users.get_current_user()
        if user and users.is_current_user_admin():
            # Create houses
            houses = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin']
            for house in houses:
                House(house_name=house).put()

            # Create departments
            deps = [
                {'code': 'CS', 'name': 'Computer Science'},
                {'code': 'BA', 'name': 'Business Administration'},
                {'code': 'PHY', 'name': 'Physics'},
                {'code': 'MAT', 'name': 'Mathematics'},
                {'code': 'DRA', 'name': 'Drama'},
                {'code': 'ECE', 'name': 'Electrical Engineering'},
            ]
            for dep in deps:
                Department(id = dep['code'], dept_name = dep['name']).put()

            # Create 40 classes for department, update depts
            classes_count = 40
            for dept in deps:
                department_key = ndb.Key('Department', dept['code'])
                department_obj = department_key.get()
                for i in range(classes_count):
                    class_full_name = "%s - Class %d" % (dept['name'] ,i)
                    class_key = Class(id='%s-%d'%(dept['code'], i),
                          class_full_name = class_full_name,
                        department = department_key).put()
                    department_obj.classes.append(class_key)
                department_obj.put()

            # Create students
            students_count = 1000
            random.seed()
            all_classes = Class.query().fetch()
            all_houses = House.query().fetch()
            for i in range(students_count):
                house = random.choice(all_houses)
                house_key = house.key
                student_name = 'Student %d'% i
                student_year = random.randint(1,4)
                current_classes = random.sample(all_classes, 5)
                current_classes_keys = [el.key for el in current_classes]
                all_classes_keys = [el.key for el in all_classes]
                leftovers = set(all_classes_keys) - set(current_classes_keys)
                completed_classes_keys = random.sample(leftovers, 6*(student_year-1))
                student_key = Student(
                    student_name = student_name,
                    student_year = student_year,
                    current_classes = current_classes_keys,
                    completed_classes = completed_classes_keys,
                    house = house_key).put()
                house.students.append(student_key)
                for el in current_classes:
                    el.students_enrolled.append(student_key)
            # save new status of houses and current classes
            for house in all_houses:
                house.put()
            for current_class in all_classes:
                current_class.put()

        elif user and not users.is_current_user_admin():
            self.redirect(users.create_logout_url('/create_entries'))
        else:
            self.redirect(users.create_login_url('/create_entries'))
예제 #50
0
async def put(id: int, classe: ClassBaseIn):
    await Class.filter(id=id).update(**classe.dict(exclude_unset=True))
    return await ClassBaseOut.from_queryset_single(Class.get(id=id))
예제 #51
0
def load_data(file_path, teachers_empty_space, groups_empty_space,
              subjects_order):
    """
    Loads and processes input data, initialises helper structures.
    :param file_path: path to file with input data
    :param teachers_empty_space: dictionary where key = name of the teacher, values = list of rows where it is in
    :param groups_empty_space: dictionary where key = group index, values = list of rows where it is in
    :param subjects_order: dictionary where key = (name of the subject, index of the group), value = [int, int, int]
    where ints represent start times (row in matrix) for types of classes P, V and L respectively. If start time is -1
    it means that that subject does not have that type of class.
    :return: Data(groups, teachers, classes, classrooms)
    """
    with open(file_path) as file:
        data = json.load(file)

    # classes: dictionary where key = index of a class, value = class
    classes = {}
    # classrooms: dictionary where key = index, value = classroom name
    classrooms = {}
    # teachers: dictionary where key = teachers' name, value = index
    teachers = {}
    # groups: dictionary where key = name of the group, value = index
    groups = {}
    class_list = []

    for cl in data['Classes']:
        new_group = cl['Groups']
        new_teacher = cl['Teacher']

        # initialise for empty space of teachers
        if new_teacher not in teachers_empty_space:
            teachers_empty_space[new_teacher] = []

        new = Class(new_group, new_teacher, cl['Subject'], cl['Tip'],
                    cl['Duration'], cl['Classroom'])
        # add groups
        for group in new_group:
            if group not in groups:
                groups[group] = len(groups)
                # initialise for empty space of groups
                groups_empty_space[groups[group]] = []

        # add teacher
        if new_teacher not in teachers:
            teachers[new_teacher] = len(teachers)
        class_list.append(new)

    # shuffle mostly because of teachers
    random.shuffle(class_list)
    # add classrooms
    for cl in class_list:
        classes[len(classes)] = cl

    # every class is assigned a list of classrooms he can be in as indexes (later columns of matrix)
    for type in data['Classrooms']:
        for name in data['Classrooms'][type]:
            new = Classroom(name, type)
            classrooms[len(classrooms)] = new

    # every class has a list of groups marked by its index, same for classrooms
    for i in classes:
        cl = classes[i]

        classroom = cl.classrooms
        index_classrooms = []
        # add classrooms
        for index, c in classrooms.items():
            if c.type == classroom:
                index_classrooms.append(index)
        cl.classrooms = index_classrooms

        class_groups = cl.groups
        index_groups = []
        for name, index in groups.items():
            if name in class_groups:
                # initialise order of subjects
                if (cl.subject, index) not in subjects_order:
                    subjects_order[(cl.subject, index)] = [-1, -1, -1]
                index_groups.append(index)
        cl.groups = index_groups

    return Data(groups, teachers, classes, classrooms)