Enroll a user.

        Create a new user enrollment for a course or section.
772167
def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_self_enrolled=None, enrollment_self_enrollment_code=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - enrollment[user_id]
        """The ID of the user to be enrolled in the course."""
        data["enrollment[user_id]"] = enrollment_user_id

        # REQUIRED - enrollment[type]
        """Enroll the user as a student, teacher, TA, observer, or designer. If no
        value is given, the type will be inferred by enrollment[role] if supplied,
        otherwise 'StudentEnrollment' will be used."""
        self._validate_enum(enrollment_type, ["StudentEnrollment", "TeacherEnrollment", "TaEnrollment", "ObserverEnrollment", "DesignerEnrollment"])
        data["enrollment[type]"] = enrollment_type

        # OPTIONAL - enrollment[role]
        """Assigns a custom course-level role to the user."""
        if enrollment_role is not None:
            data["enrollment[role]"] = enrollment_role

        # OPTIONAL - enrollment[role_id]
        """Assigns a custom course-level role to the user."""
        if enrollment_role_id is not None:
            data["enrollment[role_id]"] = enrollment_role_id

        # OPTIONAL - enrollment[enrollment_state]
        """If set to 'active,' student will be immediately enrolled in the course.
        Otherwise they will be required to accept a course invitation. Default is
        'invited.'.
        
        If set to 'inactive', student will be listed in the course roster for
        teachers, but will not be able to participate in the course until
        their enrollment is activated."""
        if enrollment_enrollment_state is not None:
            self._validate_enum(enrollment_enrollment_state, ["active", "invited", "inactive"])
            data["enrollment[enrollment_state]"] = enrollment_enrollment_state

        # OPTIONAL - enrollment[course_section_id]
        """The ID of the course section to enroll the student in. If the
        section-specific URL is used, this argument is redundant and will be
        ignored."""
        if enrollment_course_section_id is not None:
            data["enrollment[course_section_id]"] = enrollment_course_section_id

        # OPTIONAL - enrollment[limit_privileges_to_course_section]
        """If set, the enrollment will only allow the user to see and interact with
        users enrolled in the section given by course_section_id.
        * For teachers and TAs, this includes grading privileges.
        * Section-limited students will not see any users (including teachers
          and TAs) not enrolled in their sections.
        * Users may have other enrollments that grant privileges to
          multiple sections in the same course."""
        if enrollment_limit_privileges_to_course_section is not None:
            data["enrollment[limit_privileges_to_course_section]"] = enrollment_limit_privileges_to_course_section

        # OPTIONAL - enrollment[notify]
        """If true, a notification will be sent to the enrolled user.
        Notifications are not sent by default."""
        if enrollment_notify is not None:
            data["enrollment[notify]"] = enrollment_notify

        # OPTIONAL - enrollment[self_enrollment_code]
        """If the current user is not allowed to manage enrollments in this
        course, but the course allows self-enrollment, the user can self-
        enroll as a student in the default section by passing in a valid
        code. When self-enrolling, the user_id must be 'self'. The
        enrollment_state will be set to 'active' and all other arguments
        will be ignored."""
        if enrollment_self_enrollment_code is not None:
            data["enrollment[self_enrollment_code]"] = enrollment_self_enrollment_code

        # OPTIONAL - enrollment[self_enrolled]
        """If true, marks the enrollment as a self-enrollment, which gives
        students the ability to drop the course if desired. Defaults to false."""
        if enrollment_self_enrolled is not None:
            data["enrollment[self_enrolled]"] = enrollment_self_enrolled

        # OPTIONAL - enrollment[associated_user_id]
        """For an observer enrollment, the ID of a student to observe. The
        caller must have +manage_students+ permission in the course.
        This is a one-off operation; to automatically observe all a
        student's enrollments (for example, as a parent), please use
        the {api:UserObserveesController#create User Observees API}."""
        if enrollment_associated_user_id is not None:
            data["enrollment[associated_user_id]"] = enrollment_associated_user_id

        self.logger.debug("POST /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, single_item=True)
382235
def add_user(self, name: str, email: str) -> models.User:
        """"""
        new_user = self.User(name=name, email=email)
        self.add_commit(new_user)
        return new_user
248799
def add_user(self, ):
        
        i = self.user_tablev.currentIndex()
        item = i.internalPointer()
        if item:
            user = item.internal_data()
            if self._project:
                self._project.users.add(user)
            else:
                self._task.users.add(user)
            self.users.append(user)
            item.set_parent(None)
740535
def create_user(self, name, password, is_super=False):
        
        statement = ddl.CreateUser(
            name=name, password=password, is_super=is_super
        )
        self._execute(statement)
491838
def add_role(user, roles):
        
        def _add_role(role):
            user_role = UserRole()
            user_role.user_id = user.user_id
            user_role.role_id = role.role_id
            db.session.add(user_role)
            db.session.commit()
        [_add_role(role) for role in roles]
225003
async def create(self, **kwargs):
        '''  '''
        return await super(EntryResource, self).create(user=self.request['user'])
1369673
def create_user(username, password=None, email=None, first_name="", last_name="",
                role="MEMBER", login_method=None):
    

    if not login_method:
        login_method = "email" if "@" in username else "username"

    def cb():
        return _user(models.AuthUser.new(username=username,
                                         password=password,
                                         email=email,
                                         first_name=first_name,
                                         last_name=last_name,
                                         login_method=login_method,
                                         role=role))

    return signals.create_user(cb)
919660
def list_your_courses(self, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, state=None):
        
        path = {}
        data = {}
        params = {}

        # OPTIONAL - enrollment_type
        """When set, only return courses where the user is enrolled as this type. For
        example, set to "teacher" to return only courses where the user is
        enrolled as a Teacher.  This argument is ignored if enrollment_role is given."""
        if enrollment_type is not None:
            self._validate_enum(enrollment_type, ["teacher", "student", "ta", "observer", "designer"])
            params["enrollment_type"] = enrollment_type

        # OPTIONAL - enrollment_role
        """Deprecated
        When set, only return courses where the user is enrolled with the specified
        course-level role.  This can be a role created with the
        {api:RoleOverridesController#add_role Add Role API} or a base role type of
        'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment',
        or 'DesignerEnrollment'."""
        if enrollment_role is not None:
            params["enrollment_role"] = enrollment_role

        # OPTIONAL - enrollment_role_id
        """When set, only return courses where the user is enrolled with the specified
        course-level role.  This can be a role created with the
        {api:RoleOverridesController#add_role Add Role API} or a built_in role type of
        'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment',
        or 'DesignerEnrollment'."""
        if enrollment_role_id is not None:
            params["enrollment_role_id"] = enrollment_role_id

        # OPTIONAL - enrollment_state
        """When set, only return courses where the user has an enrollment with the given state.
        This will respect section/course/term date overrides."""
        if enrollment_state is not None:
            self._validate_enum(enrollment_state, ["active", "invited_or_pending", "completed"])
            params["enrollment_state"] = enrollment_state

        # OPTIONAL - include
        """- "needs_grading_count": Optional information to include with each Course.
          When needs_grading_count is given, and the current user has grading
          rights, the total number of submissions needing grading for all
          assignments is returned.
        - "syllabus_body": Optional information to include with each Course.
          When syllabus_body is given the user-generated html for the course
          syllabus is returned.
        - "public_description": Optional information to include with each Course.
          When public_description is given the user-generated text for the course
          public description is returned.
        - "total_scores": Optional information to include with each Course.
          When total_scores is given, any student enrollments will also
          include the fields 'computed_current_score', 'computed_final_score',
          'computed_current_grade', and 'computed_final_grade' (see Enrollment
          documentation for more information on these fields). This argument
          is ignored if the course is configured to hide final grades.
        - "current_grading_period_scores": Optional information to include with
          each Course. When current_grading_period_scores is given and total_scores
          is given, any student enrollments will also include the fields
          'multiple_grading_periods_enabled',
          'totals_for_all_grading_periods_option', 'current_grading_period_title',
          'current_grading_period_id', current_period_computed_current_score',
          'current_period_computed_final_score',
          'current_period_computed_current_grade', and
          'current_period_computed_final_grade' (see Enrollment documentation for
          more information on these fields). In addition, when this argument is
          passed, the course will have a 'multiple_grading_periods_enabled' attribute
          on it. This argument is ignored if the course is configured to hide final
          grades or if the total_scores argument is not included.
        - "term": Optional information to include with each Course. When
          term is given, the information for the enrollment term for each course
          is returned.
        - "course_progress": Optional information to include with each Course.
          When course_progress is given, each course will include a
          'course_progress' object with the fields: 'requirement_count', an integer
          specifying the total number of requirements in the course,
          'requirement_completed_count', an integer specifying the total number of
          requirements in this course that have been completed, and
          'next_requirement_url', a string url to the next requirement item, and
          'completed_at', the date the course was completed (null if incomplete).
          'next_requirement_url' will be null if all requirements have been
          completed or the current module does not require sequential progress.
          "course_progress" will return an error message if the course is not
          module based or the user is not enrolled as a student in the course.
        - "sections": Section enrollment information to include with each Course.
          Returns an array of hashes containing the section ID (id), section name
          (name), start and end dates (start_at, end_at), as well as the enrollment
          type (enrollment_role, e.g. 'StudentEnrollment').
        - "storage_quota_used_mb": The amount of storage space used by the files in this course
        - "total_students": Optional information to include with each Course.
          Returns an integer for the total amount of active and invited students.
        - "passback_status": Include the grade passback_status
        - "favorites": Optional information to include with each Course.
          Indicates if the user has marked the course as a favorite course.
        - "teachers": Teacher information to include with each Course.
          Returns an array of hashes containing the {api:Users:UserDisplay UserDisplay} information
          for each teacher in the course.
        - "observed_users": Optional information to include with each Course.
          Will include data for observed users if the current user has an
          observer enrollment.
        - "tabs": Optional information to include with each Course.
          Will include the list of tabs configured for each course.  See the
          {api:TabsController#index List available tabs API} for more information."""
        if include is not None:
            self._validate_enum(include, ["needs_grading_count", "syllabus_body", "public_description", "total_scores", "current_grading_period_scores", "term", "course_progress", "sections", "storage_quota_used_mb", "total_students", "passback_status", "favorites", "teachers", "observed_users"])
            params["include"] = include

        # OPTIONAL - state
        """If set, only return courses that are in the given state(s).
        By default, "available" is returned for students and observers, and
        anything except "deleted", for all other enrollment types"""
        if state is not None:
            self._validate_enum(state, ["unpublished", "available", "completed", "deleted"])
            params["state"] = state

        self.logger.debug("GET /api/v1/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses".format(**path), data=data, params=params, all_pages=True)
583939
def create_admin(ctx):
    """"""

    try:
        admin = _create_user(ctx)
        admin.roles.append('admin')

        admin.save()
        log("Done")
    except KeyError:
        log('User already exists', lvl=warn)
1026034
def create(cls, user_id, github_id=None, name=None, **kwargs):
        """"""
        with db.session.begin_nested():
            obj = cls(user_id=user_id, github_id=github_id, name=name,
                      **kwargs)
            db.session.add(obj)
        return obj
708000
def create_from_registration(cls, reg, **kwargs):
        '''
        
        '''
        submissionUser = kwargs.pop('submissionUser', None)
        collectedByUser = kwargs.pop('collectedByUser', None)
        status = kwargs.pop('status',Invoice.PaymentStatus.unpaid)

        new_invoice = cls(
            firstName=reg.firstName,
            lastName=reg.lastName,
            email=reg.email,
            grossTotal=reg.totalPrice,
            total=reg.priceWithDiscount,
            submissionUser=submissionUser,
            collectedByUser=collectedByUser,
            buyerPaysSalesTax=getConstant('registration__buyerPaysSalesTax'),
            status=status,
            data=kwargs,
        )

        if isinstance(reg, Registration):
            new_invoice.finalRegistration = reg
            ter_set = reg.eventregistration_set.all()
        elif isinstance(reg, TemporaryRegistration):
            new_invoice.temporaryRegistration = reg
            ter_set = reg.temporaryeventregistration_set.all()
        else:
            raise ValueError('Object passed is not a registration.')

        new_invoice.calculateTaxes()
        new_invoice.save()

        # Now, create InvoiceItem records for each EventRegistration
        for ter in ter_set:
            # Discounts and vouchers are always applied equally to all items at initial
            # invoice creation.
            item_kwargs = {
                'invoice': new_invoice,
                'grossTotal': ter.price,
            }

            if new_invoice.grossTotal > 0:
                item_kwargs.update({
                    'total': ter.price * (new_invoice.total / new_invoice.grossTotal),
                    'taxes': new_invoice.taxes * (ter.price / new_invoice.grossTotal),
                    'fees': new_invoice.fees * (ter.price / new_invoice.grossTotal),
                })
            else:
                item_kwargs.update({
                    'total': ter.price,
                    'taxes': new_invoice.taxes,
                    'fees': new_invoice.fees,
                })

            if isinstance(ter,TemporaryEventRegistration):
                item_kwargs['temporaryEventRegistration'] = ter
            elif isinstance(ter,EventRegistration):
                item_kwargs['finalEventRegistration'] = ter

            this_item = InvoiceItem(**item_kwargs)
            this_item.save()

        return new_invoice
1109419
def create_course_section(self, course_id, course_section_end_at=None, course_section_name=None, course_section_restrict_enrollments_to_section_dates=None, course_section_sis_section_id=None, course_section_start_at=None, enable_sis_reactivation=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # OPTIONAL - course_section[name]
        """The name of the section"""
        if course_section_name is not None:
            data["course_section[name]"] = course_section_name

        # OPTIONAL - course_section[sis_section_id]
        """The sis ID of the section"""
        if course_section_sis_section_id is not None:
            data["course_section[sis_section_id]"] = course_section_sis_section_id

        # OPTIONAL - course_section[start_at]
        """Section start date in ISO8601 format, e.g. 2011-01-01T01:00Z"""
        if course_section_start_at is not None:
            data["course_section[start_at]"] = course_section_start_at

        # OPTIONAL - course_section[end_at]
        """Section end date in ISO8601 format. e.g. 2011-01-01T01:00Z"""
        if course_section_end_at is not None:
            data["course_section[end_at]"] = course_section_end_at

        # OPTIONAL - course_section[restrict_enrollments_to_section_dates]
        """Set to true to restrict user enrollments to the start and end dates of the section."""
        if course_section_restrict_enrollments_to_section_dates is not None:
            data["course_section[restrict_enrollments_to_section_dates]"] = course_section_restrict_enrollments_to_section_dates

        # OPTIONAL - enable_sis_reactivation
        """When true, will first try to re-activate a deleted section with matching sis_section_id if possible."""
        if enable_sis_reactivation is not None:
            data["enable_sis_reactivation"] = enable_sis_reactivation

        self.logger.debug("POST /api/v1/courses/{course_id}/sections with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("POST", "/api/v1/courses/{course_id}/sections".format(**path), data=data, params=params, single_item=True)
1305510
def add_user(self, **kwargs):
        """"""
        user = self.UserClass(**kwargs)
        if hasattr(user, 'active'):
            user.active = True
        self.db_adapter.add_object(user)
        return user
272093
def add_to_user(self, name, **attrs):
        
        user = self.get_user(name=name)
        attrs_ = user['user']
        attrs_.update(**attrs)
922515
def add_user(self, user, is_admin=False):
        
        users_count = self.users.all().count()
        if users_count == 0:
            is_admin = True
        # TODO get specific org user?
        org_user = self._org_user_model.objects.create(
            user=user, organization=self, is_admin=is_admin
        )
        if users_count == 0:
            # TODO get specific org user?
            self._org_owner_model.objects.create(
                organization=self, organization_user=org_user
            )

        # User added signal
        user_added.send(sender=self, user=user)
        return org_user
503645
def register_user(self, user):
        
        self.users[user.index] = {'known_items': set()}
        self.n_user += 1
1372672
private void createNewUser() throws CmsException {

        //Password was checked by validator before
        String ou = m_ou.getValue();
        if (!ou.endsWith("/")) {
            ou += "/";
        }
        CmsUser user = m_cms.createUser(ou + m_loginname.getValue(), m_pw.getPassword1(), "", null);
        updateUser(user);
        m_cms.writeUser(user);
        if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_group.getValue())) {
            m_cms.addUserToGroup(user.getName(), m_group.getValue());
        }
        OpenCms.getRoleManager().addUserToRole(m_cms, (CmsRole)m_role.getValue(), user.getName());
        m_user = user;

    }