Пример #1
0
 def __init__(self,
              id: str,
              name: str,
              description: str,
              meals: list,
              openingHours: tuple = None,
              color: RGB = None,
              feedback: tuple = None):
     """
     Creates a counter object with unique (see uniqueness of location) ID, name, description, a list of meals
     offered there, openingHours (optional), color (optional) and feedbackTime (optional)
     @param id: string
     @param name: string
     @param description: string
     @param openingHours: optional, pair of datetime denoting opening and closing hours
     @param color: optional, RGB
     @param feedback: optional, pair of datetime denoting the interval during which feedback can be provided
     @param meals: list of Meal
     """
     self._id = id
     self._name = name
     self._description = description
     self._openingHours = openingHours
     self._color = color
     self._feedback = feedback
     self._meals = meals
     self._lock = RWLock()
Пример #2
0
 def __init__(self,
              mealID: int,
              name: str,
              notices: list,
              components: list,
              prices: dict = None,
              knownMealID: str = None,
              pricingNotice: str = None,
              category: str = None):
     """
     Creates a new meal. Each Meal has a name, a list of notices and a list components its made up of, a dictionary
     of prices assigning prices to priceTiers and optionally a knownMealID, a pricingNotice to be displayed instead
     of the prices and a category.
     @param mealID: id
     @param name: string
     @param notices: list of Notices
     @param components: list of Components
     @param prices: optional, dictionary of PriceTier and float
     @param knownMealID: optional, a (unique) string
     @param pricingNotice: optional, string
     @param category: optional, string
     """
     self._mealID = mealID
     self._name = name
     self._notices = notices
     self._components = components
     self._prices = prices
     self._knownMealID = knownMealID
     self._pricingNotice = pricingNotice
     self._category = category
     self._lock = RWLock()
Пример #3
0
 def __init__(self, moreDict):
     self._lock = RWLock()
     try:
         self.timeStamp = dateParser.parse(moreDict['linksLastChanged'])
         self.language = moreDict['language']
         self.links = parseMoreLinks(moreDict['links'], self.language)
     except ValueError as e:
         pass
Пример #4
0
 def __init__(self, query: str):
     """
     Constructor for a search item.
     """
     self._query = query
     self._lastChanged = datetime.now()
     self._searchResults = []
     self._lock = RWLock()
Пример #5
0
 def __init__(self):
     """
     Creates a new HelpfulNumberModel.
     """
     self._lastChanged = None
     self._UPDATE_THRESHOLD = timedelta(days=1)
     self._helpfulNumbers = {}  # a dict of language to list
     self._lock = RWLock()
Пример #6
0
 def __init__(self, name: str, notices: list):
     """
     Creates the component of a meal. Each component has a name and a list of notices concerning itself
     @param name: string
     @param notices: list of Notices
     """
     self._name = name
     self._notices = notices
     self._lock = RWLock()
Пример #7
0
 def __init__(self, tierId: str, name: str):
     """
     Creates a priceTier object. Each priceTier has a (unique) id and a name
     @param tierId: str
     @param name: str
     """
     self._lock = RWLock()
     self._id = tierId
     self._name = name
Пример #8
0
    def __init__(self,
                 firstname: str,
                 lastname: str,
                 academicTitle: str,
                 gender: str,
                 officeHour: str,
                 remarks: str,
                 postalCode: str,
                 city: str,
                 street: str,
                 office: str,
                 building: str,
                 phone: str,
                 fax: str,
                 mail: str,
                 webpage: str,
                 functions: list,
                 imageLink: str = None):
        """
        should not need a lock, since it should never be written to except for initialization
        :param firstname:
        :param lastname:
        :param academicTitle:
        :param gender:
        :param officeHour:
        :param remarks:
        :param postalCode:
        :param city:
        :param street:
        :param office:
        :param building:
        :param phone:
        :param fax:
        :param mail:
        :param webpage:
        """
        self._imageLink = imageLink
        self._webpage = webpage
        self._mail = mail
        self._fax = fax
        self._phone = phone
        self._building = building
        self._office = office
        self._street = street
        self._city = city
        self._postalCode = postalCode
        self._remarks = remarks
        self._officeHour = officeHour
        self._gender = gender
        self._academicTitle = academicTitle
        self._lastname = lastname
        self._firstname = firstname
        self._functions = functions  # list of PersonFunctionDetails

        self.lock = RWLock()
Пример #9
0
 def __init__(self, date: datetime, isPast: bool, counters: list):
     """
     Creates a ServingDay. Each ServingDay has its actual date, whether it lies in the past and a list of Counters
     @param date: datetime object denoting the date
     @param isPast: boolean, saying whether this day lies in the past
     @param counters: a list of Counters offered at this date
     """
     self._date = date
     self._isPast = isPast
     self._counters = counters
     self._lock = RWLock()
Пример #10
0
 def __init__(self, id: str, name: str, isAllergen: bool, isNegated: bool):
     """
     Creates a new notice. Each notice has a unique (see location) id, a readable name and knows whether it
     is an allergen or whether it denotes the absence or existence of itself.
     The name gets put in lowercase with just the first letter capitalized.
     @param id: string
     @param name: string
     @param isAllergen: bool
     @param isNegated: bool, if True the component is not included
     """
     self._id = id
     self._name = name.capitalize() if name is not None else name
     self._isAllergen = isAllergen
     self._isNegated = isNegated
     self._lock = RWLock()
Пример #11
0
 def __init__(self, id: str, name: str, description: str):
     """
     Creates a food location. Each location has a unique ID by which it will be distinguished, a name that will
     be displayed and a description. The uniqueness is not enforced here but should be in the MensaModel that
     manages all locations. We assume the uniqueness due to the MensaAPI documentation.
     Additionally each location has a list "menu", that is not assigned upon creation.
     Should the mensaAPI eventually provide opening hours, they should also be stored here, rather than in the
     separate MensaInfoModel
     @param id: a string containing the locations id
     @param name: a string containing a human readable name
     @param description: a string containing a description
     """
     self._id = id
     self._name = name
     self._description = description
     self._menu = []
     self._lock = RWLock()
Пример #12
0
 def __init__(self,
              locationInfoID: str,
              name: str,
              description: str,
              imageLink: str = None):
     """
     Creates a location info. This is necessary since the mensa API (for now) doesn't provide all needed information
     in the App. Updates to this should be done by parsing a file located on the Server.
     @param locationInfoID: str
     @param name: str
     @param description: str
     @param imageLink: str
     """
     self._locationInfoLock = RWLock()
     self._locationInfoID = locationInfoID
     self._name = name
     self._description = description
     self._imageLink = imageLink
Пример #13
0
class ServingDay:
    def __init__(self, date: datetime, isPast: bool, counters: list):
        """
        Creates a ServingDay. Each ServingDay has its actual date, whether it lies in the past and a list of Counters
        @param date: datetime object denoting the date
        @param isPast: boolean, saying whether this day lies in the past
        @param counters: a list of Counters offered at this date
        """
        self._date = date
        self._isPast = isPast
        self._counters = counters
        self._lock = RWLock()

    def setDate(self, date: datetime):
        """
        Setter for the date
        @param date: datetime object
        """
        self._lock.acquire_write()
        try:
            self._date = date
        finally:
            self._lock.release()

    def setIsPast(self, isPast: bool):
        """
        Setter for the isPast field
        @param isPast: bool
        """
        self._lock.acquire_write()
        try:
            self._isPast = isPast
        finally:
            self._lock.release()

    def setCounters(self, counters: list):
        """
        Setter for the counters
        @param counters: list of Counters
        """
        self._lock.acquire_write()
        try:
            self._counters = counters
        finally:
            self._lock.release()

    def getDate(self):
        """
        Getter for the date
        @return: datetime object
        """
        self._lock.acquire_read()
        try:
            return self._date
        finally:
            self._lock.release()

    def getIsPast(self):
        """
        Getter for the isPast field
        @return: bool
        """
        self._lock.acquire_read()
        try:
            return self._isPast
        finally:
            self._lock.release()

    def getCounters(self):
        """
        Getter for the counters
        @return: list of Counters
        """
        self._lock.acquire_read()
        try:
            return self._counters
        finally:
            self._lock.release()
Пример #14
0
class Location:
    def __init__(self, id: str, name: str, description: str):
        """
        Creates a food location. Each location has a unique ID by which it will be distinguished, a name that will
        be displayed and a description. The uniqueness is not enforced here but should be in the MensaModel that
        manages all locations. We assume the uniqueness due to the MensaAPI documentation.
        Additionally each location has a list "menu", that is not assigned upon creation.
        Should the mensaAPI eventually provide opening hours, they should also be stored here, rather than in the
        separate MensaInfoModel
        @param id: a string containing the locations id
        @param name: a string containing a human readable name
        @param description: a string containing a description
        """
        self._id = id
        self._name = name
        self._description = description
        self._menu = []
        self._lock = RWLock()

    def __eq__(self, other):
        """
        Equals for locations. A location is the same as another one, iff their ids match
        @param other: object
        @return: bool
        """
        if not isinstance(other, Location):
            return False
        self._lock.acquire_read()
        try:
            return self._id == other.getID()
        finally:
            self._lock.release()

    def __hash__(self):
        """
        Hash for location. Uses the id.
        @return: int
        """
        self._lock.acquire_read()
        try:
            return hash(self._id)
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the location's name
        @param name: string of the name
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def setID(self, id: str):
        """
        Setter for the location's ID
        @param id: string of the ID
        """
        self._lock.acquire_write()
        try:
            self._id = id
        finally:
            self._lock.release()

    def setDescription(self, description: str):
        """
        Setter for the location's description
        @param description: string of the description
        """
        self._lock.acquire_write()
        try:
            self._description = description
        finally:
            self._lock.release()

    def setMenu(self, menu):
        """
        Setter for the location's menu.
        @param menu: list of ServingDay
        """
        self._lock.acquire_write()
        try:
            self._menu = menu
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the location's description
        @return: string of the name
        """
        self._lock.acquire_read()
        try:
            if self._id == 'sb':
                return 'Saarbrücken'
            if self._id == 'hom':
                return 'Homburg'
            else:
                return self._name
        finally:
            self._lock.release()

    def getID(self):
        """
        Getter for the location's ID
        @return: string of the ID
        """
        self._lock.acquire_read()
        try:
            return self._id
        finally:
            self._lock.release()

    def getDescription(self):
        """
        Getter for the location's description
        @return: string of the description
        """
        self._lock.acquire_read()
        try:
            return self._description
        finally:
            self._lock.release()

    def getMenu(self, date: datetime = None):
        """
        Getter for the location's menu. If specified, the only element in the list will be the one with date date. Else,
        all ServingDays will be returned.
        @param date: datetime (optional, default: None), date of the requested menu
        @return: list of ServingDay
        """
        self._lock.acquire_read()
        try:
            if date is None:
                return self._menu
            else:
                for day in self._menu:
                    if (date.day, date.month) == (day.getDate().day,
                                                  day.getDate().month):
                        return [day]

                return []
        finally:
            self._lock.release()
Пример #15
0
class MoreModel:
    def __init__(self, moreDict):
        self._lock = RWLock()
        try:
            self.timeStamp = dateParser.parse(moreDict['linksLastChanged'])
            self.language = moreDict['language']
            self.links = parseMoreLinks(moreDict['links'], self.language)
        except ValueError as e:
            pass

    def getTime(self):
        self._lock.acquire_read()
        try:
            return self.timeStamp
        finally:
            self._lock.release()

    def getLinks(self):
        self._lock.acquire_read()
        try:
            if self.links == None:
                return []
            else:
                return self.links
        finally:
            self._lock.release()

    def getLanguage(self):
        self._lock.acquire_read()
        try:
            if self.language is None:
                return ""
            else:
                return self.language
        finally:
            self._lock.release()
Пример #16
0
class Meal:
    def __init__(self,
                 mealID: int,
                 name: str,
                 notices: list,
                 components: list,
                 prices: dict = None,
                 knownMealID: str = None,
                 pricingNotice: str = None,
                 category: str = None):
        """
        Creates a new meal. Each Meal has a name, a list of notices and a list components its made up of, a dictionary
        of prices assigning prices to priceTiers and optionally a knownMealID, a pricingNotice to be displayed instead
        of the prices and a category.
        @param mealID: id
        @param name: string
        @param notices: list of Notices
        @param components: list of Components
        @param prices: optional, dictionary of PriceTier and float
        @param knownMealID: optional, a (unique) string
        @param pricingNotice: optional, string
        @param category: optional, string
        """
        self._mealID = mealID
        self._name = name
        self._notices = notices
        self._components = components
        self._prices = prices
        self._knownMealID = knownMealID
        self._pricingNotice = pricingNotice
        self._category = category
        self._lock = RWLock()

    def __eq__(self, other):
        """
        Equality for Meal. Equality holds iff the the name, notices, components, prices, knownMealID, pricingNotice and
        category are equal.
        @param other: object
        @return: bool
        """
        if not isinstance(other, Meal):
            return False
        self._lock.acquire_read()
        try:
            nameEq = self._name == other.getName()
            noticeEq = CollectionCounter(self._notices) == CollectionCounter(
                other.getNotices())
            componentEq = CollectionCounter(
                self._components) == CollectionCounter(other.getComponents())
            if self._prices is not None:
                if other.getPrices() is not None:
                    priceEq = CollectionCounter(
                        self._prices.items()) == CollectionCounter(
                            other.getPrices().items())
                else:
                    return False
            else:
                if other.getPrices() is not None:
                    return False
                else:
                    priceEq = True
            knownMealEq = self._knownMealID == other.getKnownMealID()
            pricingNoticeEq = self._pricingNotice == other.getPricingNotice()
            categoryEq = self._category == other.getCategory()

            return nameEq and noticeEq and componentEq and priceEq and knownMealEq and pricingNoticeEq and categoryEq
        finally:
            self._lock.release()

    def __hash__(self):
        """
        Hash for Meal
        @return: int
        """
        self._lock.acquire_read()
        try:
            nameHash = hash(self._name)
            noticeHash = sum([hash(notice) for notice in self._notices])
            componentHash = sum(
                [hash(component) for component in self._components])
            if self._prices is None:
                priceHash = hash(self._prices)
            else:
                priceHash = sum(
                    [hash(pricePoint) for pricePoint in self._prices.items()])
            knownMealHash = hash(self._knownMealID)
            pricingNoticeHash = hash(self._pricingNotice)
            categoryHash = hash(self._category)

            return nameHash + noticeHash + componentHash + priceHash + knownMealHash + pricingNoticeHash + categoryHash
        finally:
            self._lock.release()

    def setID(self, mealID: int):
        """
        Setter for the id
        @param mealID: int
        """
        self._lock.acquire_write()
        try:
            self._mealID = mealID
        finally:
            self._lock.release()

    def getID(self):
        """
        Getter for the id
        @return: int
        """
        self._lock.acquire_read()
        try:
            return self._mealID
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the name
        @param name: string
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the name
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._name
        finally:
            self._lock.release()

    def setNotices(self, notices: list):
        """
        Setter for the notices
        @param notices: list of Notices
        """
        self._lock.acquire_write()
        try:
            self._notices = notices
        finally:
            self._lock.release()

    def getNotices(self):
        """
        Getter for the notices
        @return: list of Notices
        """
        self._lock.acquire_read()
        try:
            return self._notices
        finally:
            self._lock.release()

    def setComponents(self, components: list):
        """
        Setter for the components
        @param components: list of Components
        """
        self._lock.acquire_write()
        try:
            self._components = components
        finally:
            self._lock.release()

    def getComponents(self):
        """
        Getter for the components
        @return: list of Components
        """
        self._lock.acquire_read()
        try:
            return self._components
        finally:
            self._lock.release()

    def setPrices(self, prices: dict):
        """
        Setter for the prices
        @param prices: dict of string to float
        """
        self._lock.acquire_write()
        try:
            self._prices = prices
        finally:
            self._lock.release()

    def getPrices(self):
        """
        Getter for the prices
        @return: dict of string to float
        """
        self._lock.acquire_read()
        try:
            return self._prices
        finally:
            self._lock.release()

    def setKnownMealID(self, knownMealID: str):
        """
        Setter for the known meal id
        @param knownMealID: string
        """
        self._lock.acquire_write()
        try:
            self._knownMealID = knownMealID
        finally:
            self._lock.release()

    def getKnownMealID(self):
        """
        Getter for the known meal id
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._knownMealID
        finally:
            self._lock.release()

    def setPricingNotice(self, pricingNotice: str):
        """
        Setter for the pricing notice
        @param pricingNotice: string
        """
        self._lock.acquire_write()
        try:
            self._pricingNotice = pricingNotice
        finally:
            self._lock.release()

    def getPricingNotice(self):
        """
        Getter for the pricing notice
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._pricingNotice
        finally:
            self._lock.release()

    def setCategory(self, category: str):
        """
        Setter for the category
        @param category: string
        """
        self._lock.acquire_write()
        try:
            self._category = category
        finally:
            self._lock.release()

    def getCategory(self):
        """
        Getter for the category
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._category
        finally:
            self._lock.release()
Пример #17
0
class SearchItem:
    def __init__(self, query: str):
        """
        Constructor for a search item.
        """
        self._query = query
        self._lastChanged = datetime.now()
        self._searchResults = []
        self._lock = RWLock()

    def update(self, results: list):
        """
        Updates the search item by adding all entries in results, that are not yet in the searchResults.
        @param results: list of GeneralPerson
        """
        self._lock.acquire_write()
        try:
            for r in results:
                if r not in self._searchResults:
                    self._searchResults.append(r)

            self._lastChanged = datetime.now()
        finally:
            self._lock.release()

    def sortResults(self):
        """
        Sorts the results by the following hierarchical rules:
        1) Show people first, whose last name contains a word beginning with the search query
        2) Then show people, whose first name contains a word beginning with the search query
        3) Then show the rest
        Within the categories, use lexicographical order first within the last names and then within the first names
        """
        # Sort is stable, i.e. keeps the order of elements that are compared as equal
        # Hence sort according to the hierarchical rules in reverse order
        self._lock.acquire_write()
        try:
            self._searchResults.sort(
                key=lambda gp: gp.getFirstname())  # sort by first names
            self._searchResults.sort(
                key=lambda gp: gp.getLastname())  # sort by last names
            self._searchResults.sort(
                key=lambda gp: hasWordBeginningWith(sentence=gp.getFirstname(),
                                                    query=self._query),
                reverse=True)  # rule 2), need reverse, since True > False
            self._searchResults.sort(
                key=lambda gp: hasWordBeginningWith(sentence=gp.getLastname(),
                                                    query=self._query),
                reverse=True)  # rule 1), need reverse, since True > False

            self._lastChanged = datetime.now()
        finally:
            self._lock.release()

    def addCoolGuys(self):
        """
        EasterEgg, adds the cool guys to the search item
        """
        self._lock.acquire_write()
        try:
            self._searchResults.insert(
                0, GeneralPerson('Varsha', 'Gattu', 'Ramenator', -6))
            self._searchResults.insert(
                0, GeneralPerson('Serdar', 'Durdyyev', '', -5))
            self._searchResults.insert(
                0,
                GeneralPerson('Matias', 'Klimpel',
                              'Appreciator of Vogon Poetry', -4))
            self._searchResults.insert(
                0, GeneralPerson('Julien', 'Schanz', 'Smooth Operator', -3))
            self._searchResults.insert(
                0, GeneralPerson('Anthony', 'Heggen', 'Vampire', -2))
            self._searchResults.insert(
                0, GeneralPerson('Ali', 'Alhasani', 'The App Guy', -1))
            self._lastChanged = datetime.now()
        finally:
            self._lock.release()

    def addTheBoss(self):
        """
        EasterEgg, adds the boss to the search item
        """
        self._lock.acquire_write()
        try:
            self._searchResults.insert(
                0, GeneralPerson('Andreas', 'Zeller', 'The Boss', -7))

            self._lastChanged = datetime.now()
        finally:
            self._lock.release()

    def getQuery(self):
        """
        Getter for the query
        @return: str
        """
        self._lock.acquire_read()
        try:
            return self._query
        finally:
            self._lock.release()

    def getSearchResults(self, page: int, pageSize: int):
        """
        Getter for the search results on page with pageSize
        @param page: int
        @param pageSize: int
        @return: list of GeneralPerson
        """
        self._lock.acquire_read()
        try:
            if not hasPage(page=page,
                           pageSize=pageSize,
                           itemCount=self.getItemCount()):
                return []
            return self._searchResults[page * pageSize:(page + 1) * pageSize]
        finally:
            self._lock.release()

    def getItemCount(self):
        """
        Returns the number of search results
        @return: int
        """
        self._lock.acquire_read()
        try:
            return len(self._searchResults)
        finally:
            self._lock.release()

    def getLastUpdated(self):
        """
        Getter for the last update time
        @return: datetime
        """
        self._lock.acquire_read()
        try:
            return self._lastChanged
        finally:
            self._lock.release()
Пример #18
0
from datetime import datetime
from source.models.EventModel import EventModel
from source.models.NewsAndEventsModel import NewsAndEventsModel
from typing import List
from source.ReadWriteLock import RWLock
from source.Constants import SEMESTER_TERMINE_CATEGORY_STRING, NEWSFEED_UPDATE_INTERVAL_IN_SECONDS
import copy
from source.models.CategoryModel import Category

newsFeedLock = RWLock()


class NewsFeedModel:
    def __init__(self,
                 newsAndEvents: List[NewsAndEventsModel],
                 events: List[EventModel],
                 lastUpdated=datetime(1970, 1, 1, 0, 0, 0)):
        """
        :param newsAndEvents: a dictionary from a language code (as string) to a list of NewsAndEventModels
        :param events: a dictionary from a language code (as string) to a list of EventModels
        :param lastUpdated: a datetime object indicating, when the data stored in the model was fetched
        """
        self.newsAndEvents = newsAndEvents
        self.events = events
        self.lastUpdated = lastUpdated
        self.categories = {'lastChange': datetime.now(), 'categories': []}
        self.eventCategories = {'lastChange': datetime.now(), 'categories': []}

    def pageExists(self, itemList, page, pageSize):
        newsFeedLock.acquire_read()
        try:
Пример #19
0
class Component:
    def __init__(self, name: str, notices: list):
        """
        Creates the component of a meal. Each component has a name and a list of notices concerning itself
        @param name: string
        @param notices: list of Notices
        """
        self._name = name
        self._notices = notices
        self._lock = RWLock()

    def __eq__(self, other):
        """
        Equality for Component holds iff the name and the notices are equal
        @param other: object
        @return: bool
        """
        if not isinstance(other, Component):
            return False
        self._lock.acquire_read()
        try:
            noticeEq = CollectionCounter(self._notices) == CollectionCounter(
                other.getNotices())

            return self._name == other.getName() and noticeEq
        finally:
            self._lock.release()

    def __hash__(self):
        """
        Hash for Component
        @return: int
        """
        self._lock.acquire_read()
        try:
            noticeHash = sum([hash(notice) for notice in self._notices])
            return hash(self._name) + noticeHash
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the name
        @param name: string
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the name
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._name
        finally:
            self._lock.release()

    def setNotices(self, notices: list):
        """
        Setter for the notices
        @param notices: list of Notices
        """
        self._lock.acquire_write()
        try:
            self._notices = notices
        finally:
            self._lock.release()

    def getNotices(self):
        """
        Getter for the notices
        @return: list of Notices
        """
        self._lock.acquire_read()
        try:
            return self._notices
        finally:
            self._lock.release()
Пример #20
0
class Notice:
    def __init__(self, id: str, name: str, isAllergen: bool, isNegated: bool):
        """
        Creates a new notice. Each notice has a unique (see location) id, a readable name and knows whether it
        is an allergen or whether it denotes the absence or existence of itself.
        The name gets put in lowercase with just the first letter capitalized.
        @param id: string
        @param name: string
        @param isAllergen: bool
        @param isNegated: bool, if True the component is not included
        """
        self._id = id
        self._name = name.capitalize() if name is not None else name
        self._isAllergen = isAllergen
        self._isNegated = isNegated
        self._lock = RWLock()

    def __eq__(self, other):
        """
        Equality for notices. A notice is the same as another one, iff the ids match
        @param other: object
        @return: bool
        """
        if not isinstance(other, Notice):
            return False
        self._lock.acquire_read()
        try:
            return self._id == other.getID()
        finally:
            self._lock.release()

    def __hash__(self):
        """
        hash function for notices, should return the same hash for Notices that are __eq__
        :return: the hash value for the Notice object in question
        """
        self._lock.acquire_read()
        try:
            return self._id.__hash__()
        finally:
            self._lock.release()

    def setID(self, id: str):
        """
        Setter for the id
        @param id: string
        """
        self._lock.acquire_write()
        try:
            self._id = id
        finally:
            self._lock.release()

    def getID(self):
        """
        Getter for the id
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._id
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the name
        @param name: string
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the name
        @return: string
        """
        self._lock.acquire_read()
        try:
            return self._name
        finally:
            self._lock.release()

    def setIsAllergen(self, isAllergen: bool):
        """
        Setter for isAllergen
        @param isAllergen: bool
        """
        self._lock.acquire_write()
        try:
            self._isAllergen = isAllergen
        finally:
            self._lock.release()

    def getIsAllergen(self):
        """
        Getter for isAllergen
        @return: bool
        """
        self._lock.acquire_read()
        try:
            return self._isAllergen
        finally:
            self._lock.release()

    def setIsNegated(self, isNegated: bool):
        """
        Setter for isNegated
        @param isNegated: bool
        """
        self._lock.acquire_write()
        try:
            self._isNegated = isNegated
        finally:
            self._lock.release()

    def getIsNegated(self):
        """
        Getter for isNegated
        @return: bool
        """
        self._lock.acquire_read()
        try:
            return self._isNegated
        finally:
            self._lock.release()
Пример #21
0
from datetime import datetime
from collections import Counter as CollectionCounter
from source.ReadWriteLock import RWLock
from source.Constants import MENSA_UPDATE_THRESHOLD_WORKING_HOURS

mensaLock = RWLock()


class MensaModel:
    def __init__(self):
        """
        Creates a new mensaModel object. It has dictionaries of language codes to the following data structures:
        empty lists for locations and baseData like notices, price tiers,
        known meals, a dictionary of mealID to (meal, counter), a dictionary of locationID to locationInfo,
        as well as an empty dictionary for global messages.
        These fields should only get filled via the method update.
        Upon creation the date lastUpdated is set to None.
        """
        self.locations = {}
        self.notices = {}
        self.priceTiers = {}
        self.knownMeals = {}
        self.globalMessage = {}
        self.mealDictionary = {}
        self.locationInfoDictionary = {}
        self.lastUpdated = None
        self.UPDATE_THRESHOLD = MENSA_UPDATE_THRESHOLD_WORKING_HOURS
        self.filtersLastChanged = {}

    def update(self,
               baseData: dict,
Пример #22
0
class Counter:
    def __init__(self,
                 id: str,
                 name: str,
                 description: str,
                 meals: list,
                 openingHours: tuple = None,
                 color: RGB = None,
                 feedback: tuple = None):
        """
        Creates a counter object with unique (see uniqueness of location) ID, name, description, a list of meals
        offered there, openingHours (optional), color (optional) and feedbackTime (optional)
        @param id: string
        @param name: string
        @param description: string
        @param openingHours: optional, pair of datetime denoting opening and closing hours
        @param color: optional, RGB
        @param feedback: optional, pair of datetime denoting the interval during which feedback can be provided
        @param meals: list of Meal
        """
        self._id = id
        self._name = name
        self._description = description
        self._openingHours = openingHours
        self._color = color
        self._feedback = feedback
        self._meals = meals
        self._lock = RWLock()

    def __eq__(self, other):
        """
        Equality for Counters. Equality holds, iff the ids match
        @param other: object
        @return: bool
        """
        if not isinstance(other, Counter):
            return False

        self._lock.acquire_read()
        try:
            return other.getID() == self._id
        finally:
            self._lock.release()

    def __hash__(self):
        """
        Hash for Counters. Uses the id
        @return: int
        """
        self._lock.acquire_read()
        try:
            return hash(self._id)
        finally:
            self._lock.release()

    def setID(self, id: str):
        """
        Setter for the id
        @param id: string
        """
        self._lock.acquire_write()
        try:
            self._id = id
        finally:
            self._lock.release()

    def getID(self):
        """
        Getter for the id
        @return: string containing id
        """
        self._lock.acquire_read()
        try:
            return self._id
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the name
        @param name: string
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the name
        @return: string containing the name
        """
        self._lock.acquire_read()
        try:
            return self._name
        finally:
            self._lock.release()

    def setDescription(self, description: str):
        """
        Setter for the description
        @param description: string
        """
        self._lock.acquire_write()
        try:
            self._description = description
        finally:
            self._lock.release()

    def getDescription(self):
        """
        Getter for the description
        @return: string containing description
        """
        self._lock.acquire_read()
        try:
            return self._description
        finally:
            self._lock.release()

    def setOpeningHours(self, openingHours: tuple):
        """
        Setter for the opening hours
        @param openingHours: pair of datetime denoting opening and closing hours
        """
        self._lock.acquire_write()
        try:
            self._openingHours = openingHours
        finally:
            self._lock.release()

    def getOpeningHours(self):
        """
        Getter for the opening hours
        @return: pair of datetime denoting opening and closing hours
        """
        self._lock.acquire_read()
        try:
            return self._openingHours
        finally:
            self._lock.release()

    def setColor(self, color: RGB):
        """
        Setter for the color
        @param color: RGB
        """
        self._lock.acquire_write()
        try:
            self._color = color
        finally:
            self._lock.release()

    def getColor(self):
        """
        Getter for the color
        @return: RGB
        """
        self._lock.acquire_read()
        try:
            return self._color
        finally:
            self._lock.release()

    def setFeedback(self, feedback: tuple):
        """
        Setter for the feedback time
        @param feedback: pair of datetime denoting the interval during which feedback can be provided
        """
        self._lock.acquire_write()
        try:
            self._feedback = feedback
        finally:
            self._lock.release()

    def getFeedback(self):
        """
        Getter for the feedback time
        @return: pair of datetime denoting the interval during which feedback can be provided
        """
        self._lock.acquire_read()
        try:
            return self._feedback
        finally:
            self._lock.release()

    def setMeals(self, meals: list):
        """
        Setter for the meals
        @param meals: list of Meal
        """
        self._lock.acquire_write()
        try:
            self._meals = meals
        finally:
            self._lock.release()

    def getMeals(self):
        """
        Getter for the meals
        @return: list of Meal
        """
        self._lock.acquire_read()
        try:
            return self._meals
        finally:
            self._lock.release()
Пример #23
0
class DetailedPerson:
    def __init__(self,
                 firstname: str,
                 lastname: str,
                 academicTitle: str,
                 gender: str,
                 officeHour: str,
                 remarks: str,
                 postalCode: str,
                 city: str,
                 street: str,
                 office: str,
                 building: str,
                 phone: str,
                 fax: str,
                 mail: str,
                 webpage: str,
                 functions: list,
                 imageLink: str = None):
        """
        should not need a lock, since it should never be written to except for initialization
        :param firstname:
        :param lastname:
        :param academicTitle:
        :param gender:
        :param officeHour:
        :param remarks:
        :param postalCode:
        :param city:
        :param street:
        :param office:
        :param building:
        :param phone:
        :param fax:
        :param mail:
        :param webpage:
        """
        self._imageLink = imageLink
        self._webpage = webpage
        self._mail = mail
        self._fax = fax
        self._phone = phone
        self._building = building
        self._office = office
        self._street = street
        self._city = city
        self._postalCode = postalCode
        self._remarks = remarks
        self._officeHour = officeHour
        self._gender = gender
        self._academicTitle = academicTitle
        self._lastname = lastname
        self._firstname = firstname
        self._functions = functions  # list of PersonFunctionDetails

        self.lock = RWLock()

    def __str__(self):
        self.lock.acquire_read()
        try:
            return "Firstname: {}\nLastname: {}\nAcademic Title: {}\nGender: {}\nOfficeHour: {}\nRemark: {}\n" \
                   "Address: {}, {}\n{}\n{} {}\nPhone: {}\nFax: {}\nE-Mail: {}\n" \
                   "Website: {}".format(self._firstname, self._lastname, self._academicTitle, self._gender,
                                        self._officeHour, self._remarks, self._office, self._building, self._street,
                                        self._postalCode, self._city, self._phone, self._fax, self._mail, self._webpage)
        finally:
            self.lock.release()

    def getFirstname(self):
        """
        Getter for the firstname.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._firstname
        finally:
            self.lock.release()

    def getLastname(self):
        """
        Getter for the lastname.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._lastname
        finally:
            self.lock.release()

    def getAcademicTitle(self):
        """
        Getter for the academic title.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._academicTitle
        finally:
            self.lock.release()

    def getGender(self, language: str):
        """
        Getter for the gender
        @param language: str
        @return: str
        """
        self.lock.acquire_read()
        try:
            if self._gender == 'männlich':
                if language == 'de':
                    return 'männlich'
                elif language == 'en':
                    return 'male'
                elif language == 'fr':
                    return 'masculin'
                else:
                    return 'männlich'
            elif self._gender == 'weiblich':
                if language == 'de':
                    return 'weiblich'
                elif language == 'en':
                    return 'female'
                elif language == 'fr':
                    return 'féminine'
                else:
                    return 'weiblich'
            else:
                if language == 'de':
                    return 'unbekannt'
                elif language == 'en':
                    return 'unknown'
                elif language == 'fr':
                    return 'inconnu'
                else:
                    return 'unbekannt'
        finally:
            self.lock.release()

    def getOfficeHour(self):
        """
        Getter for the office hour.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._officeHour
        finally:
            self.lock.release()

    def getRemark(self):
        """
        Getter for the remark.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._remarks
        finally:
            self.lock.release()

    def getOffice(self):
        """
        Getter for the office.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._office
        finally:
            self.lock.release()

    def getBuilding(self):
        """
        Getter for the building.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._building
        finally:
            self.lock.release()

    def getStreet(self):
        """
        Getter for the street.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._street
        finally:
            self.lock.release()

    def getPostalCode(self):
        """
        Getter for the postal code
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._postalCode
        finally:
            self.lock.release()

    def getCity(self):
        """
        Getter for the city.
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._city
        finally:
            self.lock.release()

    def getPhone(self):
        """
        Getter for the phone
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._phone
        finally:
            self.lock.release()

    def getFax(self):
        """
        Getter for the fax
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._fax
        finally:
            self.lock.release()

    def getMail(self):
        """
        Getter for the mail
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._mail
        finally:
            self.lock.release()

    def getWebpage(self):
        """
        Getter for the webpage
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._webpage
        finally:
            self.lock.release()

    def getFunctions(self):
        """
        Getter for the functions
        @return: list of PersonFunctionDetails
        """
        self.lock.acquire_read()
        try:
            return self._functions
        finally:
            self.lock.release()

    def getImageLink(self):
        """
        Getter for the image link
        @return: str
        """
        self.lock.acquire_read()
        try:
            return self._imageLink
        finally:
            self.lock.release()

    def setImageLink(self, link: str):
        """
        Setter for the image link
        @param link: str
        """
        self.lock.acquire_write()
        try:
            self._imageLink = link
        finally:
            self.lock.release()

    def setRemark(self, remarks: str):
        """
        Setter for the remarks
        @param remarks: str
        """
        self.lock.acquire_write()
        try:
            self._remarks = remarks
        finally:
            self.lock.release()
Пример #24
0
class LocationInfo:
    def __init__(self,
                 locationInfoID: str,
                 name: str,
                 description: str,
                 imageLink: str = None):
        """
        Creates a location info. This is necessary since the mensa API (for now) doesn't provide all needed information
        in the App. Updates to this should be done by parsing a file located on the Server.
        @param locationInfoID: str
        @param name: str
        @param description: str
        @param imageLink: str
        """
        self._locationInfoLock = RWLock()
        self._locationInfoID = locationInfoID
        self._name = name
        self._description = description
        self._imageLink = imageLink

    def setID(self, locationInfoID: str):
        """
        Setter for the ID
        @param locationInfoID: string
        """
        self._locationInfoLock.acquire_write()
        self._locationInfoID = locationInfoID
        self._locationInfoLock.release()

    def getID(self):
        """
        Getter for the ID
        @return: string
        """
        self._locationInfoLock.acquire_read()
        lid = self._locationInfoID
        self._locationInfoLock.release()
        return lid

    def setName(self, name: str):
        """
        Setter for the name
        @param name: string
        """
        self._locationInfoLock.acquire_write()
        self._name = name
        self._locationInfoLock.release()

    def getName(self):
        """
        Getter for the name
        @return: string
        """
        self._locationInfoLock.acquire_read()
        name = self._name
        self._locationInfoLock.release()
        return name

    def setDescription(self, description: str):
        """
        Setter for the description
        @param description: string
        """
        self._locationInfoLock.acquire_write()
        self._description = description
        self._locationInfoLock.release()

    def getDescription(self):
        """
        Getter for the description
        @return: string
        """
        self._locationInfoLock.acquire_read()
        desc = self._description
        self._locationInfoLock.release()
        return desc

    def setImageLink(self, imageLink: str):
        """
        Setter for the image link
        @param imageLink: string
        """
        self._locationInfoLock.acquire_write()
        self._imageLink = imageLink
        self._locationInfoLock.release()

    def getImageLink(self):
        """
        Getter for the image link
        @return: string
        """
        self._locationInfoLock.acquire_read()
        il = self._imageLink
        self._locationInfoLock.release()
        return il
Пример #25
0
class PriceTier:
    def __init__(self, tierId: str, name: str):
        """
        Creates a priceTier object. Each priceTier has a (unique) id and a name
        @param tierId: str
        @param name: str
        """
        self._lock = RWLock()
        self._id = tierId
        self._name = name

    def __eq__(self, other):
        """
        Equality for PriceTier holds iff the ids are the same
        @param other: object
        @return: bool
        """
        if not isinstance(other, PriceTier):
            return False
        self._lock.acquire_read()
        try:
            return self._id == other.getId()
        finally:
            self._lock.release()

    def __hash__(self):
        """
        Hash for PriceTier
        @return: int
        """
        self._lock.acquire_read()
        try:
            return hash(self._id)
        finally:
            self._lock.release()

    def setId(self, tierId: str):
        """
        Setter for the id
        @param tierId: str
        """
        self._lock.acquire_write()
        try:
            self._id = tierId
        finally:
            self._lock.release()

    def getId(self):
        """
        Getter for the id
        @return: str
        """
        self._lock.acquire_read()
        try:
            return self._id
        finally:
            self._lock.release()

    def setName(self, name: str):
        """
        Setter for the name
        @param name: str
        """
        self._lock.acquire_write()
        try:
            self._name = name
        finally:
            self._lock.release()

    def getName(self):
        """
        Getter for the name
        @return: str
        """
        self._lock.acquire_read()
        try:
            return self._name
        finally:
            self._lock.release()
Пример #26
0
class HelpfulNumberModel:
    def __init__(self):
        """
        Creates a new HelpfulNumberModel.
        """
        self._lastChanged = None
        self._UPDATE_THRESHOLD = timedelta(days=1)
        self._helpfulNumbers = {}  # a dict of language to list
        self._lock = RWLock()

    def update(self, helpfulNumbers: dict):
        """
        Updates the model. Checks, if there has been an actual change to set lastUpdated.
        @param helpfulNumbers: dict of language code to list of HelpfulNumbers
        """
        self._lock.acquire_write()
        try:
            updated = False
            for language in helpfulNumbers.keys():
                if language not in self._helpfulNumbers.keys():
                    # new language, there has been an actual update
                    self._helpfulNumbers[language] = helpfulNumbers[language]
                    updated = True
                else:
                    # language is known, check if the items are the same
                    if not collectionCounter(
                            helpfulNumbers[language]) == collectionCounter(
                                self._helpfulNumbers[language]):
                        # there is an actual update
                        self._helpfulNumbers[language] = helpfulNumbers[
                            language]
                        updated = True

            if updated:
                self._lastChanged = datetime.now()
        finally:
            self._lock.release()

    def isUpToDate(self):
        """
        Compares the current time to the lastUpdated. If the difference exceeds a predefined threshold, return False
        @return True, if the lastUpdated time is less than self._UPDATE_THRESHOLD away from now
        """
        self._lock.acquire_read()
        try:
            if self._lastChanged is None:
                return False

            return (datetime.now() -
                    self._lastChanged) < self._UPDATE_THRESHOLD
        finally:
            self._lock.release()

    def getHelpfulNumbers(self, language: str):
        """
        Getter for the helpful numbers in a language. If this language is not known returns German as a default
        @param language: str
        @return: list of HelpfulNumber
        """
        self._lock.acquire_read()
        try:
            if language not in self._helpfulNumbers.keys():
                return self._helpfulNumbers['de']
            else:
                return self._helpfulNumbers[language]
        finally:
            self._lock.release()

    def getLastChanged(self):
        """
        Getter for lastChanged
        @return: datetime
        """
        self._lock.acquire_read()
        try:
            return self._lastChanged
        finally:
            self._lock.release()
Пример #27
0
import json
from dateutil import parser as dateParser
from source.ReadWriteLock import RWLock

mapLock = RWLock()


class MapModel:
    def __init__(self, filepath, updateTime):
        self.filepath = filepath
        self.updateTime = updateTime

    def getFilepath(self):
        mapLock.acquire_read()
        try:
            return self.filepath
        finally:
            mapLock.release()

    def getCoordinateList(self):
        """
        :return: the map data as a list
        """
        mapLock.acquire_read()
        try:
            with open(self.filepath, 'r') as f:
                mapJSONString = f.read()
                mapJSONDict = json.loads(mapJSONString)
                #mapData = mapJSONDict['mapInfo']
                return mapJSONDict
        finally:
Пример #28
0
from datetime import datetime, timedelta
from source.ReadWriteLock import RWLock
from collections import Counter as collectionCounter
from source.Constants import DIRECTORY_CACHE_THRESHOLD, DIRECTORY_IMAGE_BASE_LINK

directoryLock = RWLock()


def hasWordBeginningWith(sentence: str, query: str) -> bool:
    """
    Checks if the sentence contains a word beginning with the query.
    By default, words are considered substrings separated by any of the characters in this string: " ,.'-".
    If one of these symbols appears in the query, the sentence is not split by these characters.
    This method should be used to sort the list of GeneralPerson in a SearchItem
    @param sentence: str
    @param query: str
    @return: bool
    """
    words = [sentence]

    # split the sentence into words by each valid separator
    for char in " ,.'-":
        if char not in query:
            newWords = []
            # split each word by the next separator
            for word in words:
                newWords += word.split(char)

            words = newWords  # replace the previous list of words by the new one

    # Check if one of the words begins with the query, ignore casing