Flag any entries from previous days where users forgot to sign
    out.

    :param session: SQLAlchemy session through which to access the database.
    :param today: (optional) The current date as a `datetime.date` object. Used for testing.
351679
def flag_forgotten_entries(session, today=None):
     # noqa
    today = date.today() if today is None else today

    forgotten = (
        session
        .query(Entry)
        .filter(Entry.time_out.is_(None))
        .filter(Entry.forgot_sign_out.is_(False))
        .filter(Entry.date < today)
    )

    for entry in forgotten:
        e = sign_out(entry, forgot=True)
        logger.debug('Signing out forgotten entry: {}'.format(e))
        session.add(e)

    session.commit()
9544
def newlogins(sessions):
    
    if not sessions:
        return [], []
    users = {}
    dates = {}

    for session in sessions:
        user = session.user
        # time value is discarded to aggregate on days only
        date = session.started_at.strftime("%Y/%m/%d")
        # keep the info only it's the first time we encounter a user
        if user not in users:
            users[user] = date
            # build the list of users on a given day
            if date not in dates:
                dates[date] = [user]
            else:
                dates[date].append(user)

    data = []
    total = []
    previous = 0
    for date in sorted(dates.keys()):
        # print u"{} : {}".format(date, len(dates[date]))
        date_epoch = unix_time_millis(datetime.strptime(date, "%Y/%m/%d"))
        data.append({"x": date_epoch, "y": len(dates[date])})
        previous += len(dates[date])
        total.append({"x": date_epoch, "y": previous})

    return data, total
983056
def prompt_for_existing_session(self, sessions):
        
        if not sessions:
            return None
        print("Would you like to join a previous session or create a new session?")
        for index, session in enumerate(sessions):
            print(("{id} : {creator} started at {timestamp} ({hashid})"
                   .format(id=index+1, creator=session.get('creator'),
                           timestamp=session.get('created'), hashid=session.get('id'))))
        print("{new_id} : Create a new session with the current files?"
              .format(new_id=len(sessions)+1))
        desired = input("Type the number of the session you'd like to join: ")
        try:
            outcome = int(desired.strip())
        except:
            outcome = len(sessions)+1
            log.warning("Could not parse int for choice")

        if outcome >= len(sessions):
            log.info("Chose to start new session")
            return None
        else:
            log.info("Resuming session {}".format(outcome - 1))
            desired = sessions[outcome - 1]
            return session
337535
def undo_sign_in(entry, session=None):
     # noqa
    if session is None:
        session = Session()
    else:
        session = session

    entry_to_delete = (
        session
        .query(Entry)
        .filter(Entry.uuid == entry.uuid)
        .one_or_none()
    )

    if entry_to_delete:
        logger.info('Undo sign in: {}'.format(entry_to_delete.user_id))
        logger.debug('Undo sign in: {}'.format(entry_to_delete))
        session.delete(entry_to_delete)
        session.commit()
    else:
        error_message = 'Entry not found: {}'.format(entry)
        logger.error(error_message)
        raise ValueError(error_message)
37668
def get_last_activity(session):
    
    try:
        return datetime.strptime(session['_session_security'],
                '%Y-%m-%dT%H:%M:%S.%f')
    except AttributeError:
        #################################################################
        # * this is an odd bug in python
        # bug report: http://bugs.python.org/issue7980
        # bug explained here:
        # http://code-trick.com/python-bug-attribute-error-_strptime/
        # * sometimes, in multithreaded enviroments, we get AttributeError
        #     in this case, we just return datetime.now(),
        #     so that we are not logged out
        #   "./session_security/middleware.py", in update_last_activity
        #     last_activity = get_last_activity(request.session)
        #   "./session_security/utils.py", in get_last_activity
        #     '%Y-%m-%dT%H:%M:%S.%f')
        #   AttributeError: _strptime
        #
        #################################################################

        return datetime.now()
    except TypeError:
        return datetime.now()
1086881
def logout(self, all_session=False):
        
        # initialize the counter of the number of destroyed sesisons
        session_nb = 0
        # save the current user username before flushing the session
        username = self.request.session.get("username")
        if username:
            if all_session:
                logger.info("Logging out user %s from all sessions." % username)
            else:
                logger.info("Logging out user %s." % username)
        users = []
        # try to get the user from the current session
        try:
            users.append(
                models.User.objects.get(
                    username=username,
                    session_key=self.request.session.session_key
                )
            )
        except models.User.DoesNotExist:
            # if user not found in database, flush the session anyway
            self.request.session.flush()

        # If all_session is set, search all of the user sessions
        if all_session:
            users.extend(
                models.User.objects.filter(
                    username=username
                ).exclude(
                    session_key=self.request.session.session_key
                )
            )

        # Iterate over all user sessions that have to be logged out
        for user in users:
            # get the user session
            session = SessionStore(session_key=user.session_key)
            # flush the session
            session.flush()
            # send SLO requests
            user.logout(self.request)
            # delete the user
            user.delete()
            # increment the destroyed session counter
            session_nb += 1
        if username:
            logger.info("User %s logged out" % username)
        return session_nb
252294
def previous_day(self):
        """"""
        return HDate(self.gdate + datetime.timedelta(-1), self.diaspora,
                     self.hebrew)
704093
def validate_session(self, session, latest_only=False):
        
        if latest_only:
            if session != self.metadata['terms'][-1]['sessions'][-1]:
                raise NoDataForPeriod(session)

        for t in self.metadata['terms']:
            if session in t['sessions']:
                return True
        raise NoDataForPeriod(session)
342574
def undo_sign_out(entry, session=None):
     # noqa
    if session is None:
        session = Session()
    else:
        session = session

    entry_to_sign_in = (
        session
        .query(Entry)
        .filter(Entry.uuid == entry.uuid)
        .one_or_none()
    )

    if entry_to_sign_in:
        logger.info('Undo sign out: {}'.format(entry_to_sign_in.user_id))
        logger.debug('Undo sign out: {}'.format(entry_to_sign_in))
        entry_to_sign_in.time_out = None
        session.add(entry_to_sign_in)
        session.commit()
    else:
        error_message = 'Entry not found: {}'.format(entry)
        logger.error(error_message)
        raise ValueError(error_message)
1046917
def where_entry_visible(query, date=None):
    

    return orm.select(
        e for e in query
        if e.status == model.PublishStatus.PUBLISHED.value or
        (e.status == model.PublishStatus.SCHEDULED.value and
         (e.utc_date <= (date or arrow.utcnow().datetime))
         )
    )
681542
def getRemainingDaysInValidation(self):
        
        delta = 0
        today = DateTime()
        down_from = self.getDownFrom() or today
        down_to = self.getDownTo()

        # one of the fields is not set, return 0 days
        if not down_from or not down_to:
            return 0
        # down_from comes after down_to?
        if down_from > down_to:
            return 0
        # calculate the time between today and down_to, even if down_from
        # is in the future.
        else:
            delta = down_to - today

        return int(math.ceil(delta))
624915
def login(self, email=None, password=None, remember=False):
        
        from flask_login import login_user
        user = self.first(email=email)
        if user is None:
            events.login_failed_nonexistent_event.send()
            return False

        # check for account being locked
        if user.is_locked():
            raise x.AccountLocked(locked_until=user.locked_until)

        # check for email being confirmed
        is_new = user.email and not user.email_new
        if is_new and not user.email_confirmed and self.require_confirmation:
            raise x.EmailNotConfirmed(email=user.email_secure)

        verified = user.verify_password(password)
        if not verified:
            user.increment_failed_logins()
            self.save(user)
            events.login_failed_event.send(user)
            return False

        # login otherwise
        login_user(user=user, remember=remember)
        user.reset_login_counter()
        self.save(user)
        events.login_event.send(user)

        # notify principal
        app = current_app._get_current_object()
        identity_changed.send(app, identity=Identity(user.id))

        # and return
        return True
660443
def transaction(self, session=None):
        
        local_session = None
        if session is None:
            local_session = session = self.create_scoped_session()
        try:
            yield session
        finally:
            # Since ``local_session`` was created locally, close it here itself
            if local_session is not None:
                # but wait!
                # http://groups.google.com/group/sqlalchemy/browse_thread/thread/7c1eb642435adde7
                # To workaround this issue with sqlalchemy, we can either:
                #  1) pass the session object explicitly
                #  2) do not close the session at all (bad idea - could lead to memory leaks)
                #
                # Till pypm implements atomic transations in client.installer,
                # we retain this hack (i.e., we choose (2) for now)
                pass
144046
def clear(self, session):
        
        try:
            sess = self.sessions[session]
        except KeyError:
            return constants.StatusCode.error_invalid_object
        return sess.clear()
1051643
def get_data(session=None, day=None, year=None):
    
    if session is None:
        user = default_user()
    else:
        user = User(token=session)
    if day is None:
        day = current_day()
        log.info("current day=%s", day)
    if year is None:
        year = most_recent_year()
        log.info("most recent year=%s", year)
    puzzle = Puzzle(year=year, day=day, user=user)
    return puzzle.input_data
387870
def today(date_time=None):
    
    ret = date_time or cst_now()
    try:
        ret = datetime(year=ret.year, month=ret.month, day=ret.day)
        if DEFAULT_TIMEZONE_AWARE:
            ret = ret.replace(
                tzinfo=psycopg2.tz.FixedOffsetTimezone(
                    name=None, offset=DEFAULT_TIMEZONE * 60))
    except Exception as ex:
        pass
    return ret
569431
def _register(self, session):
        
        if session.session_id:
            self._sessions[session.name] = session