function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def get(self): pass
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def fill_with_api_logs(self, acc): today = datetime.datetime.now() rand = random.randint(1, 100) batch = APICountBatch(date=today, account_key=acc.key().name(), counter=rand) batch.put() for ii in range(0, 10): rand = random.randint(1, 100) + 10*ii delta = datetime.timedelta(days=ii) cur_date = today - delta batch = APICountBatch(date=cur_date, account_key=acc.key().name(), counter=rand) batch.put()
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def get(self): created_logs = "" for ii in constants.TEST_ACCOUNTS: acc = accounts_dao.get(ii) if acc: self.fill_with_api_logs(acc) created_logs = acc.key().name() if created_logs: self.response.out.write("Created logs for test account " + created_logs) else: self.response.out.write("Did not create any logs, create a test account first")
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def fill_with_api_logs(self, acc): today = datetime.datetime.now() rand = random.randint(1, 100) batch = BadgePointsBatch(date=today, badgeid="badge1", account_key=acc.key().name(), counter=rand) batch.put() for ii in range(0, 10): rand = random.randint(1, 100) + 10*ii delta = datetime.timedelta(days=ii) cur_date = today - delta batch = BadgePointsBatch(date=cur_date, badgeid="badge1", account_key=acc.key().name(), counter=rand) batch.put() today = datetime.datetime.now() rand = random.randint(1, 100) batch = BadgePointsBatch(date=today, badgeid="badge2", account_key=acc.key().name(), counter=rand) batch.put() for ii in range(0, 10): rand = random.randint(1, 100) + 10*ii delta = datetime.timedelta(days=ii) cur_date = today - delta batch = BadgePointsBatch(date=cur_date, badgeid="badge2", account_key=acc.key().name(), counter=rand) batch.put()
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def get(self): created_logs = "" for ii in constants.TEST_ACCOUNTS: acc = accounts_dao.get(ii) if acc: self.fill_with_api_logs(acc) created_logs = acc.key().name() if created_logs: self.response.out.write("Created logs for test account " + created_logs) else: self.response.out.write("Did not create any logs, create a test account first")
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def fill_with_api_logs(self, acc): today = datetime.datetime.now() rand = random.randint(1, 100) batch = BadgeBatch(date=today, badgeid="badge1", account_key=acc.key().name(), counter=rand) batch.put() for ii in range(0, 10): rand = random.randint(1, 100) + 10*ii delta = datetime.timedelta(days=ii) cur_date = today - delta batch = BadgeBatch(date=cur_date, badgeid="badge1", account_key=acc.key().name(), counter=rand) batch.put() today = datetime.datetime.now() rand = random.randint(1, 100) batch = BadgeBatch(date=today, badgeid="badge2", account_key=acc.key().name(), counter=rand) batch.put() for ii in range(0, 10): rand = random.randint(1, 100) + 10*ii delta = datetime.timedelta(days=ii) cur_date = today - delta batch = BadgeBatch(date=cur_date, badgeid="badge2", account_key=acc.key().name(), counter=rand) batch.put()
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def get(self): created_logs = "" for ii in constants.TEST_ACCOUNTS: acc = accounts_dao.get(ii) if acc: self.fill_with_api_logs(acc) created_logs = acc.key().name() if created_logs: self.response.out.write("Created logs for test account " + created_logs) else: self.response.out.write("Did not create any logs, create a test account first")
nlake44/UserInfuser
[ 101, 54, 101, 3, 1311320106 ]
def _test_config(self): return TestConfig()
scylladb/scylla-cluster-tests
[ 45, 61, 45, 414, 1451430222 ]
def db_cluster(self): return DBCluster( params=self._params, common_tags=self._test_config.common_tags(), test_id=self._test_config.test_id(), )
scylladb/scylla-cluster-tests
[ 45, 61, 45, 414, 1451430222 ]
def loader_cluster(self): return LoaderCluster( params=self._params, common_tags=self._test_config.common_tags(), test_id=self._test_config.test_id(), )
scylladb/scylla-cluster-tests
[ 45, 61, 45, 414, 1451430222 ]
def monitoring_cluster(self): return MonitoringCluster( params=self._params, common_tags=self._test_config.common_tags(), test_id=self._test_config.test_id(), )
scylladb/scylla-cluster-tests
[ 45, 61, 45, 414, 1451430222 ]
def anonymous_id_for_user(user, course_id, save=True): """ Return a unique id for a (user, course) pair, suitable for inserting into e.g. personalized survey links. If user is an `AnonymousUser`, returns `None` Keyword arguments: save -- Whether the id should be saved in an AnonymousUserId object. """ # This part is for ability to get xblock instance in xblock_noauth handlers, where user is unauthenticated. if user.is_anonymous(): return None cached_id = getattr(user, '_anonymous_id', {}).get(course_id) if cached_id is not None: return cached_id # include the secret key as a salt, and to make the ids unique across different LMS installs. hasher = hashlib.md5() hasher.update(settings.SECRET_KEY) hasher.update(unicode(user.id)) if course_id: hasher.update(course_id.to_deprecated_string().encode('utf-8')) digest = hasher.hexdigest() if not hasattr(user, '_anonymous_id'): user._anonymous_id = {} # pylint: disable=protected-access user._anonymous_id[course_id] = digest # pylint: disable=protected-access if save is False: return digest try: anonymous_user_id, __ = AnonymousUserId.objects.get_or_create( defaults={'anonymous_user_id': digest}, user=user, course_id=course_id ) if anonymous_user_id.anonymous_user_id != digest: log.error( u"Stored anonymous user id %r for user %r " u"in course %r doesn't match computed id %r", user, course_id, anonymous_user_id.anonymous_user_id, digest ) except IntegrityError: # Another thread has already created this entry, so # continue pass return digest
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def has_profile_image(self): """ Convenience method that returns a boolean indicating whether or not this user has uploaded a profile image. """ return self.profile_image_uploaded_at is not None
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def set_meta(self, meta_json): # pylint: disable=missing-docstring self.meta = json.dumps(meta_json)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def requires_parental_consent(self, date=None, age_limit=None, default_requires_consent=True): """Returns true if this user requires parental consent. Args: date (Date): The date for which consent needs to be tested (defaults to now). age_limit (int): The age limit at which parental consent is no longer required. This defaults to the value of the setting 'PARENTAL_CONTROL_AGE_LIMIT'. default_requires_consent (bool): True if users require parental consent if they have no specified year of birth (default is True). Returns: True if the user requires parental consent. """ if age_limit is None: age_limit = getattr(settings, 'PARENTAL_CONSENT_AGE_LIMIT', None) if age_limit is None: return False # Return True if either: # a) The user has a year of birth specified and that year is fewer years in the past than the limit. # b) The user has no year of birth specified and the default is to require consent. # # Note: we have to be conservative using the user's year of birth as their birth date could be # December 31st. This means that if the number of years since their birth year is exactly equal # to the age limit then we have to assume that they might still not be old enough. year_of_birth = self.year_of_birth if year_of_birth is None: return default_requires_consent if date is None: date = datetime.now(UTC) return date.year - year_of_birth <= age_limit # pylint: disable=maybe-no-member
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_profile_pre_save_callback(sender, **kwargs): """ Ensure consistency of a user profile before saving it. """ user_profile = kwargs['instance'] # Remove profile images for users who require parental consent if user_profile.requires_parental_consent() and user_profile.has_profile_image: user_profile.profile_image_uploaded_at = None # Cache "old" field values on the model instance so that they can be # retrieved in the post_save callback when we emit an event with new and # old field values. user_profile._changed_fields = get_changed_fields_dict(user_profile, sender)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_profile_post_save_callback(sender, **kwargs): """ Emit analytics events after saving the UserProfile. """ user_profile = kwargs['instance'] # pylint: disable=protected-access emit_field_changed_events( user_profile, user_profile.user, sender._meta.db_table, excluded_fields=['meta'] )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_pre_save_callback(sender, **kwargs): """ Capture old fields on the user instance before save and cache them as a private field on the current model for use in the post_save callback. """ user = kwargs['instance'] user._changed_fields = get_changed_fields_dict(user, sender)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_post_save_callback(sender, **kwargs): """ Emit analytics events after saving the User. """ user = kwargs['instance'] # pylint: disable=protected-access emit_field_changed_events( user, user, sender._meta.db_table, excluded_fields=['last_login', 'first_name', 'last_name'], hidden_fields=['password'] )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def unique_id_for_user(user, save=True): """ Return a unique id for a user, suitable for inserting into e.g. personalized survey links. Keyword arguments: save -- Whether the id should be saved in an AnonymousUserId object. """ # Setting course_id to '' makes it not affect the generated hash, # and thus produce the old per-student anonymous id return anonymous_id_for_user(user, None, save=save)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def register(self, user): # MINOR TODO: Switch to crypto-secure key self.activation_key = uuid.uuid4().hex self.user = user self.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def request_change(self, email): """Request a change to a user's email. Implicitly saves the pending email change record. Arguments: email (unicode): The proposed new email for the user. Returns: unicode: The activation code to confirm the change. """ self.new_email = email self.activation_key = uuid.uuid4().hex self.save() return self.activation_key
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def create(self, user): """ This will copy over the current password, if any of the configuration has been turned on """ if not (PasswordHistory.is_student_password_reuse_restricted() or PasswordHistory.is_staff_password_reuse_restricted() or PasswordHistory.is_password_reset_frequency_restricted() or PasswordHistory.is_staff_forced_password_reset_enabled() or PasswordHistory.is_student_forced_password_reset_enabled()): return self.user = user self.password = user.password self.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_student_password_reuse_restricted(cls): """ Returns whether the configuration which limits password reuse has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_diff_pw = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE', 0 ) return min_diff_pw > 0
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_staff_password_reuse_restricted(cls): """ Returns whether the configuration which limits password reuse has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_diff_pw = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE', 0 ) return min_diff_pw > 0
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_password_reset_frequency_restricted(cls): """ Returns whether the configuration which limits the password reset frequency has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_between_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS' ) return min_days_between_reset
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_staff_forced_password_reset_enabled(cls): """ Returns whether the configuration which forces password resets to occur has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_between_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DAYS_FOR_STAFF_ACCOUNTS_PASSWORD_RESETS' ) return min_days_between_reset
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_student_forced_password_reset_enabled(cls): """ Returns whether the configuration which forces password resets to occur has been turned on """ if not settings.FEATURES['ADVANCED_SECURITY']: return False min_days_pw_reset = settings.ADVANCED_SECURITY_CONFIG.get( 'MIN_DAYS_FOR_STUDENT_ACCOUNTS_PASSWORD_RESETS' ) return min_days_pw_reset
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def should_user_reset_password_now(cls, user): """ Returns whether a password has 'expired' and should be reset. Note there are two different expiry policies for staff and students """ if not settings.FEATURES['ADVANCED_SECURITY']: return False days_before_password_reset = None if user.is_staff: if cls.is_staff_forced_password_reset_enabled(): days_before_password_reset = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DAYS_FOR_STAFF_ACCOUNTS_PASSWORD_RESETS'] elif cls.is_student_forced_password_reset_enabled(): days_before_password_reset = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DAYS_FOR_STUDENT_ACCOUNTS_PASSWORD_RESETS'] if days_before_password_reset: history = PasswordHistory.objects.filter(user=user).order_by('-time_set') time_last_reset = None if history: # first element should be the last time we reset password time_last_reset = history[0].time_set else: # no history, then let's take the date the user joined time_last_reset = user.date_joined now = timezone.now() delta = now - time_last_reset return delta.days >= days_before_password_reset return False
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_password_reset_too_soon(cls, user): """ Verifies that the password is not getting reset too frequently """ if not cls.is_password_reset_frequency_restricted(): return False history = PasswordHistory.objects.filter(user=user).order_by('-time_set') if not history: return False now = timezone.now() delta = now - history[0].time_set return delta.days < settings.ADVANCED_SECURITY_CONFIG['MIN_TIME_IN_DAYS_BETWEEN_ALLOWED_RESETS']
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_allowable_password_reuse(cls, user, new_password): """ Verifies that the password adheres to the reuse policies """ if not settings.FEATURES['ADVANCED_SECURITY']: return True if user.is_staff and cls.is_staff_password_reuse_restricted(): min_diff_passwords_required = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STAFF_PASSWORDS_BEFORE_REUSE'] elif cls.is_student_password_reuse_restricted(): min_diff_passwords_required = \ settings.ADVANCED_SECURITY_CONFIG['MIN_DIFFERENT_STUDENT_PASSWORDS_BEFORE_REUSE'] else: min_diff_passwords_required = 0 # just limit the result set to the number of different # password we need history = PasswordHistory.objects.filter(user=user).order_by('-time_set')[:min_diff_passwords_required] for entry in history: # be sure to re-use the same salt # NOTE, how the salt is serialized in the password field is dependent on the algorithm # in pbkdf2_sha256 [LMS] it's the 3rd element, in sha1 [unit tests] it's the 2nd element hash_elements = entry.password.split('$') algorithm = hash_elements[0] if algorithm == 'pbkdf2_sha256': hashed_password = make_password(new_password, hash_elements[2]) elif algorithm == 'sha1': hashed_password = make_password(new_password, hash_elements[1]) else: # This means we got something unexpected. We don't want to throw an exception, but # log as an error and basically allow any password reuse AUDIT_LOG.error(''' Unknown password hashing algorithm "{0}" found in existing password hash, password reuse policy will not be enforced!!! '''.format(algorithm)) return True if entry.password == hashed_password: return False return True
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_feature_enabled(cls): """ Returns whether the feature flag around this functionality has been set """ return settings.FEATURES['ENABLE_MAX_FAILED_LOGIN_ATTEMPTS']
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_user_locked_out(cls, user): """ Static method to return in a given user has his/her account locked out """ try: record = LoginFailures.objects.get(user=user) if not record.lockout_until: return False now = datetime.now(UTC) until = record.lockout_until is_locked_out = until and now < until return is_locked_out except ObjectDoesNotExist: return False
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def increment_lockout_counter(cls, user): """ Ticks the failed attempt counter """ record, _ = LoginFailures.objects.get_or_create(user=user) record.failure_count = record.failure_count + 1 max_failures_allowed = settings.MAX_FAILED_LOGIN_ATTEMPTS_ALLOWED # did we go over the limit in attempts if record.failure_count >= max_failures_allowed: # yes, then store when this account is locked out until lockout_period_secs = settings.MAX_FAILED_LOGIN_ATTEMPTS_LOCKOUT_PERIOD_SECS record.lockout_until = datetime.now(UTC) + timedelta(seconds=lockout_period_secs) record.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def clear_lockout_counter(cls, user): """ Removes the lockout counters (normally called after a successful login) """ try: entry = LoginFailures.objects.get(user=user) entry.delete() except ObjectDoesNotExist: return
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def num_enrolled_in(self, course_id): """ Returns the count of active enrollments in a course. 'course_id' is the course_id to return enrollments """ enrollment_number = super(CourseEnrollmentManager, self).get_query_set().filter( course_id=course_id, is_active=1 ).count() return enrollment_number
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def users_enrolled_in(self, course_id): """Return a queryset of User for every user enrolled in the course.""" return User.objects.filter( courseenrollment__course_id=course_id, courseenrollment__is_active=True )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enrolled_and_dropped_out_users(self, course_id): """Return a queryset of Users in the course.""" return User.objects.filter( courseenrollment__course_id=course_id )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __unicode__(self): return ( "[CourseEnrollment] {}: {} ({}); active: ({})" ).format(self.user, self.course_id, self.created, self.is_active)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def get_or_create_enrollment(cls, user, course_key): """ Create an enrollment for a user in a class. By default *this enrollment is not active*. This is useful for when an enrollment needs to go through some sort of approval process before being activated. If you don't need this functionality, just call `enroll()` instead. Returns a CoursewareEnrollment object. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) It is expected that this method is called from a method which has already verified the user authentication and access. """ # If we're passing in a newly constructed (i.e. not yet persisted) User, # save it to the database so that it can have an ID that we can throw # into our CourseEnrollment object. Otherwise, we'll get an # IntegrityError for having a null user_id. assert(isinstance(course_key, CourseKey)) if user.id is None: user.save() enrollment, created = CourseEnrollment.objects.get_or_create( user=user, course_id=course_key, ) # If we *did* just create a new enrollment, set some defaults if created: enrollment.mode = "honor" enrollment.is_active = False enrollment.save() return enrollment
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def get_enrollment(cls, user, course_key): """Returns a CoursewareEnrollment object. Args: user (User): The user associated with the enrollment. course_id (CourseKey): The key of the course associated with the enrollment. Returns: Course enrollment object or None """ try: return CourseEnrollment.objects.get( user=user, course_id=course_key ) except cls.DoesNotExist: return None
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_enrollment_closed(cls, user, course): """ Returns a boolean value regarding whether the user has access to enroll in the course. Returns False if the enrollment has been closed. """ # Disable the pylint error here, as per ormsbee. This local import was previously # in CourseEnrollment.enroll from courseware.access import has_access # pylint: disable=import-error return not has_access(user, 'enroll', course)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def emit_event(self, event_name): """ Emits an event to explicitly track course enrollment and unenrollment. """ try: context = contexts.course_context_from_course_id(self.course_id) assert(isinstance(self.course_id, CourseKey)) data = { 'user_id': self.user.id, 'course_id': self.course_id.to_deprecated_string(), 'mode': self.mode, } with tracker.get_tracker().context(event_name, context): tracker.emit(event_name, data) if settings.FEATURES.get('SEGMENT_IO_LMS') and settings.SEGMENT_IO_LMS_KEY: tracking_context = tracker.get_tracker().resolve_context() analytics.track(self.user_id, event_name, { 'category': 'conversion', 'label': self.course_id.to_deprecated_string(), 'org': self.course_id.org, 'course': self.course_id.course, 'run': self.course_id.run, 'mode': self.mode, }, context={ 'Google Analytics': { 'clientId': tracking_context.get('client_id') } }) except: # pylint: disable=bare-except if event_name and self.course_id: log.exception( u'Unable to emit event %s for user %s and course %s', event_name, self.user.username, # pylint: disable=no-member self.course_id, )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enroll(cls, user, course_key, mode="honor", check_access=False): """ Enroll a user in a course. This saves immediately. Returns a CoursewareEnrollment object. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_key` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `mode` is a string specifying what kind of enrollment this is. The default is "honor", meaning honor certificate. Future options may include "audit", "verified_id", etc. Please don't use it until we have these mapped out. `check_access`: if True, we check that an accessible course actually exists for the given course_key before we enroll the student. The default is set to False to avoid breaking legacy code or code with non-standard flows (ex. beta tester invitations), but for any standard enrollment flow you probably want this to be True. Exceptions that can be raised: NonExistentCourseError, EnrollmentClosedError, CourseFullError, AlreadyEnrolledError. All these are subclasses of CourseEnrollmentException if you want to catch all of them in the same way. It is expected that this method is called from a method which has already verified the user authentication. Also emits relevant events for analytics purposes. """ # All the server-side checks for whether a user is allowed to enroll. try: course = modulestore().get_course(course_key) except ItemNotFoundError: log.warning( u"User %s failed to enroll in non-existent course %s", user.username, course_key.to_deprecated_string(), ) raise NonExistentCourseError if check_access: if course is None: raise NonExistentCourseError if CourseEnrollment.is_enrollment_closed(user, course): log.warning( u"User %s failed to enroll in course %s because enrollment is closed", user.username, course_key.to_deprecated_string() ) raise EnrollmentClosedError if CourseEnrollment.objects.is_course_full(course): log.warning( u"User %s failed to enroll in full course %s", user.username, course_key.to_deprecated_string(), ) raise CourseFullError if CourseEnrollment.is_enrolled(user, course_key): log.warning( u"User %s attempted to enroll in %s, but they were already enrolled", user.username, course_key.to_deprecated_string() ) if check_access: raise AlreadyEnrolledError # User is allowed to enroll if they've reached this point. enrollment = cls.get_or_create_enrollment(user, course_key) enrollment.update_enrollment(is_active=True, mode=mode) return enrollment
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enroll_by_email(cls, email, course_id, mode="honor", ignore_errors=True): """ Enroll a user in a course given their email. This saves immediately. Note that enrolling by email is generally done in big batches and the error rate is high. For that reason, we supress User lookup errors by default. Returns a CoursewareEnrollment object. If the User does not exist and `ignore_errors` is set to `True`, it will return None. `email` Email address of the User to add to enroll in the course. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `mode` is a string specifying what kind of enrollment this is. The default is "honor", meaning honor certificate. Future options may include "audit", "verified_id", etc. Please don't use it until we have these mapped out. `ignore_errors` is a boolean indicating whether we should suppress `User.DoesNotExist` errors (returning None) or let it bubble up. It is expected that this method is called from a method which has already verified the user authentication and access. """ try: user = User.objects.get(email=email) return cls.enroll(user, course_id, mode) except User.DoesNotExist: err_msg = u"Tried to enroll email {} into course {}, but user not found" log.error(err_msg.format(email, course_id)) if ignore_errors: return None raise
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def unenroll(cls, user, course_id, skip_refund=False): """ Remove the user from a given course. If the relevant `CourseEnrollment` object doesn't exist, we log an error but don't throw an exception. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) `skip_refund` can be set to True to avoid the refund process. """ try: record = CourseEnrollment.objects.get(user=user, course_id=course_id) record.update_enrollment(is_active=False, skip_refund=skip_refund) except cls.DoesNotExist: log.error( u"Tried to unenroll student %s from %s but they were not enrolled", user, course_id )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def unenroll_by_email(cls, email, course_id): """ Unenroll a user from a course given their email. This saves immediately. User lookup errors are logged but will not throw an exception. `email` Email address of the User to unenroll from the course. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) """ try: user = User.objects.get(email=email) return cls.unenroll(user, course_id) except User.DoesNotExist: log.error( u"Tried to unenroll email %s from course %s, but user not found", email, course_id )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_enrolled(cls, user, course_key): """ Returns True if the user is enrolled in the course (the entry must exist and it must have `is_active=True`). Otherwise, returns False. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) """ if not user.is_authenticated(): return False try: record = CourseEnrollment.objects.get(user=user, course_id=course_key) return record.is_active except cls.DoesNotExist: return False
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def is_enrolled_by_partial(cls, user, course_id_partial): """ Returns `True` if the user is enrolled in a course that starts with `course_id_partial`. Otherwise, returns False. Can be used to determine whether a student is enrolled in a course whose run name is unknown. `user` is a Django User object. If it hasn't been saved yet (no `.id` attribute), this method will automatically save it before adding an enrollment for it. `course_id_partial` (CourseKey) is missing the run component """ assert isinstance(course_id_partial, CourseKey) assert not course_id_partial.run # None or empty string course_key = SlashSeparatedCourseKey(course_id_partial.org, course_id_partial.course, '') querystring = unicode(course_key.to_deprecated_string()) try: return CourseEnrollment.objects.filter( user=user, course_id__startswith=querystring, is_active=1 ).exists() except cls.DoesNotExist: return False
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enrollment_mode_for_user(cls, user, course_id): """ Returns the enrollment mode for the given user for the given course `user` is a Django User object `course_id` is our usual course_id string (e.g. "edX/Test101/2013_Fall) Returns (mode, is_active) where mode is the enrollment mode of the student and is_active is whether the enrollment is active. Returns (None, None) if the courseenrollment record does not exist. """ try: record = CourseEnrollment.objects.get(user=user, course_id=course_id) return (record.mode, record.is_active) except cls.DoesNotExist: return (None, None)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enrollments_for_user(cls, user): return CourseEnrollment.objects.filter(user=user, is_active=1)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def activate(self): """Makes this `CourseEnrollment` record active. Saves immediately.""" self.update_enrollment(is_active=True)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def change_mode(self, mode): """Changes this `CourseEnrollment` record's mode to `mode`. Saves immediately.""" self.update_enrollment(mode=mode)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def username(self): return self.user.username
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def course(self): return modulestore().get_course(self.course_id)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def create_manual_enrollment_audit(cls, user, email, state_transition, reason, enrollment=None): """ saves the student manual enrollment information """ cls.objects.create( enrolled_by=user, enrolled_email=email, state_transition=state_transition, reason=reason, enrollment=enrollment )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def get_manual_enrollment_by_email(cls, email): """ if matches returns the most recent entry in the table filtered by email else returns None. """ try: manual_enrollment = cls.objects.filter(enrolled_email=email).latest('time_stamp') except cls.DoesNotExist: manual_enrollment = None return manual_enrollment
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def get_manual_enrollment(cls, enrollment): """ if matches returns the most recent entry in the table filtered by enrollment else returns None, """ try: manual_enrollment = cls.objects.filter(enrollment=enrollment).latest('time_stamp') except cls.DoesNotExist: manual_enrollment = None return manual_enrollment
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __unicode__(self): return "[CourseEnrollmentAllowed] %s: %s (%s)" % (self.email, self.course_id, self.created)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def may_enroll_and_unenrolled(cls, course_id): """ Return QuerySet of students who are allowed to enroll in a course. Result excludes students who have already enrolled in the course. `course_id` identifies the course for which to compute the QuerySet. """ enrolled = CourseEnrollment.objects.users_enrolled_in(course_id=course_id).values_list('email', flat=True) return CourseEnrollmentAllowed.objects.filter(course_id=course_id).exclude(email__in=enrolled)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def _key(self): """ convenience function to make eq overrides easier and clearer. arbitrary decision that role is primary, followed by org, course, and then user """ return (self.role, self.org, self.course_id, self.user_id)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __hash__(self): return hash(self._key)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __unicode__(self): return "[CourseAccessRole] user: {} role: {} org: {} course: {}".format(self.user.username, self.role, self.org, self.course_id)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def get_user_by_username_or_email(username_or_email): """ Return a User object, looking up by email if username_or_email contains a '@', otherwise by username. Raises: User.DoesNotExist is lookup fails. """ if '@' in username_or_email: return User.objects.get(email=username_or_email) else: return User.objects.get(username=username_or_email)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_info(email): user, u_prof = get_user(email) print "User id", user.id print "Username", user.username print "E-mail", user.email print "Name", u_prof.name print "Location", u_prof.location print "Language", u_prof.language return user, u_prof
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def change_name(email, new_name): _user, u_prof = get_user(email) u_prof.name = new_name u_prof.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def active_user_count(): return User.objects.filter(is_active=True).count()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def add_user_to_group(user, group): utg = UserTestGroup.objects.get(name=group) utg.users.add(User.objects.get(username=user)) utg.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def add_user_to_default_group(user, group): try: utg = UserTestGroup.objects.get(name=group) except UserTestGroup.DoesNotExist: utg = UserTestGroup() utg.name = group utg.description = DEFAULT_GROUPS[group] utg.save() utg.users.add(User.objects.get(username=user)) utg.save()
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def log_successful_login(sender, request, user, **kwargs): # pylint: disable=unused-argument """Handler to log when logins have occurred successfully.""" if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"Login success - user.id: {0}".format(user.id)) else: AUDIT_LOG.info(u"Login success - {0} ({1})".format(user.username, user.email))
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def log_successful_logout(sender, request, user, **kwargs): # pylint: disable=unused-argument """Handler to log when logouts have occurred successfully.""" if settings.FEATURES['SQUELCH_PII_IN_LOGS']: AUDIT_LOG.info(u"Logout - user.id: {0}".format(request.user.id)) else: AUDIT_LOG.info(u"Logout - {0}".format(request.user))
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def enforce_single_login(sender, request, user, signal, **kwargs): # pylint: disable=unused-argument """ Sets the current session id in the user profile, to prevent concurrent logins. """ if settings.FEATURES.get('PREVENT_CONCURRENT_LOGINS', False): if signal == user_logged_in: key = request.session.session_key else: key = None if user: user.profile.set_login_session(key)
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def recent_enrollment_seconds(self): return self.recent_enrollment_time_delta
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def add_to_profile_url(self, course_key, course_name, cert_mode, cert_url, source="o", target="dashboard"): """Construct the URL for the "add to profile" button. Arguments: course_key (CourseKey): The identifier for the course. course_name (unicode): The display name of the course. cert_mode (str): The course mode of the user's certificate (e.g. "verified", "honor", "professional") cert_url (str): The download URL for the certificate. Keyword Arguments: source (str): Either "o" (for onsite/UI), "e" (for emails), or "m" (for mobile) target (str): An identifier for the occurrance of the button. """ params = OrderedDict([ ('_ed', self.company_identifier), ('pfCertificationName', self._cert_name(course_name, cert_mode).encode('utf-8')), ('pfCertificationUrl', cert_url), ('source', source) ]) tracking_code = self._tracking_code(course_key, cert_mode, target) if tracking_code is not None: params['trk'] = tracking_code return u'http://www.linkedin.com/profile/add?{params}'.format( params=urlencode(params) )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def _tracking_code(self, course_key, cert_mode, target): """Create a tracking code for the button. Tracking codes are used by LinkedIn to collect analytics about certifications users are adding to their profiles. The tracking code format is: &trk=[partner name]-[certificate type]-[date]-[target field] In our case, we're sending: &trk=edx-{COURSE ID}_{COURSE MODE}-{TARGET} If no partner code is configured, then this will return None, indicating that tracking codes are disabled. Arguments: course_key (CourseKey): The identifier for the course. cert_mode (str): The enrollment mode for the course. target (str): Identifier for where the button is located. Returns: unicode or None """ return ( u"{partner}-{course_key}_{cert_mode}-{target}".format( partner=self.trk_partner_name, course_key=unicode(course_key), cert_mode=cert_mode, target=target ) if self.trk_partner_name else None )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __unicode__(self): return "[EntranceExamConfiguration] %s: %s (%s) = %s" % ( self.user, self.course_id, self.created, self.skip_entrance_exam )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def user_can_skip_entrance_exam(cls, user, course_key): """ Return True if given user can skip entrance exam for given course otherwise False. """ can_skip = False if settings.FEATURES.get('ENTRANCE_EXAMS', False): try: record = EntranceExamConfiguration.objects.get(user=user, course_id=course_key) can_skip = record.skip_entrance_exam except EntranceExamConfiguration.DoesNotExist: can_skip = False return can_skip
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __init__(self, *args, **kwargs): """Creates a LanguageField. Accepts all the same kwargs as a CharField, except for max_length and choices. help_text defaults to a description of the ISO 639-1 set. """ kwargs.pop('max_length', None) kwargs.pop('choices', None) help_text = kwargs.pop( 'help_text', _("The ISO 639-1 language code for this language."), ) super(LanguageField, self).__init__( max_length=16, choices=settings.ALL_LANGUAGES, help_text=help_text, *args, **kwargs )
shubhdev/openedx
[ 2, 2, 2, 1, 1437064811 ]
def __init__(self, filename, **kwargs): pgsz = kwargs.pop('pagesize', 'a4') if pgsz in PAGE_SIZES: pgsz = PAGE_SIZES[pgsz][1] else: pgsz = pagesizes.A4 orient = kwargs.pop('orientation', 'portrait') if orient in PAGE_ORIENTATIONS: pgsz = PAGE_ORIENTATIONS[orient][1](pgsz) kwargs['pagesize'] = pgsz kwargs['creator'] = 'NetProfile' req = kwargs.pop('request', None) if req: u = req.user if u: kwargs['author'] = (u.name_full + ' (' + u.login + ')').strip() super(DefaultDocTemplate, self).__init__(filename, **kwargs) fr_body = frames.Frame( self.leftMargin, self.bottomMargin, self.width, self.height, id='body' ) fr_left = frames.Frame( self.leftMargin, self.bottomMargin, self.width / 2, self.height, rightPadding=12, id='left' ) fr_right = frames.Frame( self.leftMargin + self.width / 2, self.bottomMargin, self.width / 2, self.height, leftPadding=12, id='right' ) self.addPageTemplates(( doctemplate.PageTemplate(id='default', pagesize=pgsz, frames=(fr_body,)), # onPage=callback doctemplate.PageTemplate(id='2columns', pagesize=pgsz, frames=(fr_left, fr_right)) ))
nikitos/npui
[ 2, 1, 2, 1, 1404365642 ]
def _add_custom_ss(ss, custom_cfg, name): pass
nikitos/npui
[ 2, 1, 2, 1, 1404365642 ]
def _get_pdfss(req): global _pdfss return _pdfss
nikitos/npui
[ 2, 1, 2, 1, 1404365642 ]
def fixture_update_dir(request): """Fixture that creates and tears down version.txt and log files""" def create_update_dir(version="0.0.1"): def teardown(): if os.path.isfile(Launcher.version_check_log): os.remove(Launcher.version_check_log) if os.path.isfile(Launcher.version_doc): os.remove(Launcher.version_doc) request.addfinalizer(teardown) with open(Launcher.version_doc, mode='w') as version_file: version_file.write(version) return fixture_update_dir return create_update_dir
rlee287/pyautoupdate
[ 10, 3, 10, 10, 1456896357 ]
def given_tenant_id_is_registered_in_cloto(context): context.secondary_tenant_id = \ configuration_utils.config[PROPERTIES_CONFIG_FACTS_SERVICE][PROPERTIES_CONFIG_FACTS_SERVICE_OS_SECONDARY_TENANT_ID] print ("> Initiating Cloto REST Client for the secondary Tenant") context.secondary_cloto_client = ClotoClient( username=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_OS_USERNAME], password=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_OS_PASSWORD], tenant_id=context.secondary_tenant_id, auth_url=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_OS_AUTH_URL], api_protocol=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_PROTOCOL], api_host=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_HOST], api_port=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_PORT], api_resource=configuration_utils.config[PROPERTIES_CONFIG_CLOTO_SERVICE][PROPERTIES_CONFIG_SERVICE_RESOURCE]) print ("> A GET request is executed to CLOTO component, " "to init all data about that secondary tenant in its system.") _, response = context.secondary_cloto_client.\ get_tenant_id_resource_client().get_tenant_id(context.secondary_tenant_id) assert_that(response.ok, "TenantId '{}' for testing cannot be " "retrieved from CLOTO: Message: {}".format(context.secondary_tenant_id, response.text))
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def a_context_update_is_received_for_secondary_tenant(context, server_id): send_context_notification_step_helper(context, context.secondary_tenant_id, server_id)
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def new_secondaty_consumer_looking_for_messages(context): # Init RabbitMQ consumer context.secondaty_rabbitmq_consumer = RabbitMQConsumer( amqp_host=configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_SERVICE_HOST], amqp_port=configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_SERVICE_PORT], amqp_user=configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_SERVICE_USER], amqp_password=configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_SERVICE_PASSWORD]) facts_message_config = \ configuration_utils.config[PROPERTIES_CONFIG_RABBITMQ_SERVICE][PROPERTIES_CONFIG_RABBITMQ_SERVICE_FACTS_MESSAGES] context.secondaty_rabbitmq_consumer.exchange = \ facts_message_config[PROPERTIES_CONFIG_RABBITMQ_SERVICE_EXCHANGE_NAME] context.secondaty_rabbitmq_consumer.exchange_type = \ facts_message_config[PROPERTIES_CONFIG_RABBITMQ_SERVICE_EXCHANGE_TYPE] # Append consumer to the 'context' consumer list context.rabbitmq_consumer_list.append(context.secondaty_rabbitmq_consumer) # Set default window size to 2 (FACTS) - Secondary Tenant message = get_window_size_rabbitmq_message(context.secondary_tenant_id, FACTS_DEFAULT_WINDOW_SIZE) context.rabbitmq_publisher.send_message(message) # Run secondary consumer context.secondaty_rabbitmq_consumer.routing_key = context.secondary_tenant_id context.secondaty_rabbitmq_consumer.run_as_thread()
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def following_messages_are_sent_to_secondary_consumer(context): for element in context.table.rows: expected_message = dict(element.as_dict()) expected_message = _dataset_utils.prepare_data(expected_message) assert_that(expected_message, is_message_in_consumer_list(context.secondaty_rabbitmq_consumer.message_list), "A message with the expected content has not been received by the secondary RabbitMQ consumer")
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def no_messages_received_for_secondary_tenant(context): print ("> Received main list: " + str(context.secondaty_rabbitmq_consumer.message_list)) print ("> Received seconday list: " + str(context.rabbitmq_consumer.message_list)) assert_that(context.secondaty_rabbitmq_consumer.message_list, has_length(0), "Secondary RabbitMQ consumer has retrieved messages from the bus, and it should NOT")
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def notifications_are_received_by_secondary_consumer(context, number_of_notifications): assert_that(context.secondaty_rabbitmq_consumer.message_list, has_length(int(number_of_notifications)), "Secondary RabbitMQ consumer has NOT retrieved the expected number of messages from the bus")
telefonicaid/fiware-facts
[ 1, 5, 1, 4, 1398066258 ]
def __init__(self, file=None): self._file = file or sys.stdout self.prev_progress = 0 self.backwards_progress = False self.done = False self.last = 0
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def _start(self): self.prev_progress = 0 self.backwards_progress = False self.done = False self.last = 0
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def _finish(self): raise NotImplementedError()
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def _update(self, progress): self._file.write('\r') i = int(progress * self.WIDTH) self._file.write("[%-50s] %3d%%" % ('=' * i, round(progress * 100))) self._file.flush()
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def _start(self): super(ProgressReportNoTTY, self)._start() self._file.write('[' + '---|' * 9 + '----]\n[') self._file.flush()
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def _finish(self): self._file.write("]\n") self._file.flush()
pyocd/pyOCD
[ 883, 424, 883, 228, 1382710205 ]
def listwrite(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n" % item)
fredzannarbor/pagekicker-community
[ 19, 6, 19, 56, 1459730292 ]
def main(): tmpdir = "/tmp/pagekicker" #personal api key saved as api_key.txt parser = argparse.ArgumentParser() parser.add_argument('path', help = "target file or directory for NER") parser.add_argument('outfile', help = "target file for output") parser.add_argument('uuid', help = "uuid") args = parser.parse_args() in_file = args.path out_file = args.outfile uuid = args.uuid folder = os.path.join(tmpdir, uuid) print(folder) with open(in_file, 'rb') as f: text = f.read() AlchemyApi_Key = 'b887e176b6a650093c3d4ca635cd1b470be6584e' url = 'https://gateway-a.watsonplatform.net/calls/text/TextGetRankedNamedEntities' payload = { 'apikey': AlchemyApi_Key, 'outputMode': 'xml', 'text': text, 'max_items': '3' } r = requests.post(url,payload) root = ET.fromstring(r) place_list = ['City', 'Continent', 'Country', 'Facility', 'GeographicFeature',\ 'Region', 'StateOrCounty'] People = {} Places = {} Other = {} for entity in root.getiterator('entity'): if entity[0].text == 'Person': People[entity[3].text]=[entity[1].text, entity[2].text] elif entity[0].text in place_list: Places[entity[3].text] = [entity[1].text, entity[2].text] else: Other[entity[3].text] = [entity[1].text, entity[2].text] #print lists ordered by relevance Places_s = sorted(Places, key = Places.get, reverse = True) People_s = sorted(People, key = People.get, reverse = True) Other_s = sorted(Other, key = Other.get, reverse = True) with codecs.open(out_file, mode = 'w', encoding='utf-8') as o: listwrite(o, People_s) listwrite(o, Places_s) listwrite(o, Other_s) out_file = os.path.join(folder, 'People') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, People_s) out_file = os.path.join(folder, 'Places') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, Places_s) out_file = os.path.join(folder, 'Other') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, Other_s)
fredzannarbor/pagekicker-community
[ 19, 6, 19, 56, 1459730292 ]
def setUp(self): super(TestBenchmarkMem, self).setUp() self.hw_data = [('cpu', 'logical', 'number', 2), ('cpu', 'physical', 'number', 2)]
redhat-cip/hardware
[ 43, 39, 43, 6, 1417464617 ]
def test_check_mem_size(self, mock_popen, mock_cpu_socket, mock_get_memory): block_size_list = ('1K', '4K', '1M', '16M', '128M', '1G', '2G') mock_get_memory.return_value = 123456789012 for block_size in block_size_list: self.assertTrue(mem.check_mem_size(block_size, 2)) # Low memory mock_get_memory.return_value = 1 for block_size in block_size_list: self.assertFalse(mem.check_mem_size(block_size, 2))
redhat-cip/hardware
[ 43, 39, 43, 6, 1417464617 ]
def __init__(self): super(BadTokenError, self).__init__('Bad machine token')
luci/luci-py
[ 70, 40, 70, 82, 1427740754 ]
def machine_authentication(request): """Implementation of the machine authentication. See components.auth.handler.AuthenticatingHandler.get_auth_methods for details of the expected interface. Args: request: webapp2.Request with the incoming request. Returns: (auth.Identity, None) with machine ID ("bot:<fqdn>") on success or (None, None) if there's no machine token header (which means this authentication method is not applicable). Raises: BadTokenError (which is api.AuthenticationError) if machine token header is present, but the token is invalid. We also log the error details, but return only generic error message to the user. """ token = request.headers.get(MACHINE_TOKEN_HEADER) if not token: return None, None # Deserialize both envelope and the body. try: token = b64_decode(token) except TypeError as exc: log_error(request, None, exc, 'Failed to decode base64') raise BadTokenError() try: envelope = machine_token_pb2.MachineTokenEnvelope() envelope.MergeFromString(token) body = machine_token_pb2.MachineTokenBody() body.MergeFromString(envelope.token_body) except message.DecodeError as exc: log_error(request, None, exc, 'Failed to deserialize the token') raise BadTokenError() # Construct an identity of a token server that signed the token to check that # it belongs to "auth-token-servers" group. try: signer_service_account = model.Identity.from_bytes('user:' + body.issued_by) except ValueError as exc: log_error(request, body, exc, 'Bad issued_by field - %s', body.issued_by) raise BadTokenError() # Reject tokens from unknown token servers right away. if not api.is_group_member(TOKEN_SERVERS_GROUP, signer_service_account): log_error(request, body, None, 'Unknown token issuer - %s', body.issued_by) raise BadTokenError() # Check the expiration time before doing any heavier checks. now = utils.time_time() if now < body.issued_at - ALLOWED_CLOCK_DRIFT_SEC: log_error(request, body, None, 'The token is not yet valid') raise BadTokenError() if now > body.issued_at + body.lifetime + ALLOWED_CLOCK_DRIFT_SEC: log_error(request, body, None, 'The token has expired') raise BadTokenError() # Check the token was actually signed by the server. try: certs = signature.get_service_account_certificates(body.issued_by) is_valid_sig = certs.check_signature( blob=envelope.token_body, key_name=envelope.key_id, signature=envelope.rsa_sha256) if not is_valid_sig: log_error(request, body, None, 'Bad signature') raise BadTokenError() except signature.CertificateError as exc: if exc.transient: raise TransientError(str(exc)) log_error( request, body, exc, 'Unexpected error when checking the signature') raise BadTokenError() # The token is valid. Construct the bot identity. try: ident = model.Identity.from_bytes('bot:' + body.machine_fqdn) except ValueError as exc: log_error(request, body, exc, 'Bad machine_fqdn - %s', body.machine_fqdn) raise BadTokenError() # Unfortunately 'bot:*' identity namespace is shared between token-based # identities and old IP-whitelist based identity. They shouldn't intersect, # but better to enforce this. if ident == model.IP_WHITELISTED_BOT_ID: log_error(request, body, None, 'Bot ID %s is forbidden', ident.to_bytes()) raise BadTokenError() return ident, None
luci/luci-py
[ 70, 40, 70, 82, 1427740754 ]