コード例 #1
0
ファイル: sifo.py プロジェクト: yanzj/stressa
    def family(self, fam: Family):
        """
        family setter

        """
        Assertor.assert_data_types([fam], [Family])
        self._family = fam
コード例 #2
0
ファイル: signal.py プロジェクト: seemir/stressa
    def __init__(self, data: object, desc: str, style: str = "dotted", prettify_keys: bool = False,
                 length=15, **attrs):
        """
        Constructor / Instantiating class

        Parameters
        ----------
        data            : object
                          data to pass in or out from operation
        desc            : str
                          description of operation
        prettify_keys   : bool
                          True if one wants to prettify keys in data
        length          : int
                          length to apply new line, default is 15

        """
        Assertor.assert_data_types([data, desc, style, prettify_keys, length],
                                   [object, str, str, bool, int])
        if hasattr(data, "__dict__"):
            keys = data.__dict__.keys()
            self.keys = self.prettify_dict_keys(keys, length) if prettify_keys else \
                self.remove_quotation(list(keys), remove_new_line=True)
        elif isinstance(data, dict):
            keys = data.keys()
            self.keys = self.prettify_dict_keys(keys, length) if prettify_keys else \
                self.remove_quotation(list(keys), remove_new_line=True)
        else:
            self.keys = "None"
        self.desc = desc
        self.data = data
        super().__init__(name=str(uuid4()), shape="record", style=style,
                         label="keys\\<{}\\> \\n {} \\<type '{}'\\>".format(
                             self.keys, self.desc, data.__class__.__name__), **attrs)
コード例 #3
0
ファイル: ssb_payload.py プロジェクト: yanzj/stressa
    def __init__(self,
                 utlanstype: list = None,
                 sektor: list = None,
                 rentebinding: list = None,
                 tid: list = None):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        utlanstype      : list
                          type of loan, default ["70"]
        sektor          : list
                          sektor, default is ["04b"]
        rentebinding    : list
                          type of interest rate, default is ["08", "12", "10", "11", "06"]
        tid             : list
                          time frame

        """
        try:
            LOGGER.info("trying to create '{}'".format(
                self.__class__.__name__))
            Assertor.assert_data_types([utlanstype, sektor, rentebinding, tid],
                                       [(type(None), list) for _ in range(3)])
            self.utlanstype = ["70"] if not utlanstype else utlanstype
            self.sektor = ["04b"] if not sektor else sektor
            self.rentebinding = ["08", "12", "10", "11", "06"
                                 ] if not rentebinding else rentebinding
            self.tid = self._updated_table_date() if not tid else tid
            LOGGER.success("created {}".format(self.__class__.__name__))
        except Exception as ssb_payload_exception:
            LOGGER.exception(ssb_payload_exception)
            raise ssb_payload_exception
コード例 #4
0
    def extract_log(file_dir: str, exp: Exception):
        """
        static method for creating temp log file and extracting details from this file,
        for details about content, see app.log

        Parameters
        ----------
        file_dir    : str
                      name of file directory to create temp log file
        exp         : Exception
                      the exception to extract from log file

        Returns
        -------
        out         : str
                      log details about exception

        """
        Assertor.assert_data_types([file_dir, exp], [str, Exception])
        log_str = []
        file_name = "ui.log"
        error_log = logger.add(os.path.join(file_dir, file_name))
        logger.exception(exp)
        with open(os.path.join(file_dir, file_name)) as log_file:
            for lines in log_file.readlines():
                log_str.append(lines)
            logger.remove(error_log)
            log_file.close()
        return "".join(log_str)
コード例 #5
0
ファイル: finn_model.py プロジェクト: seemir/stressa
    def __init__(self, parent: QObject):
        """
        Constructor / Instantiation of class

        Parameters
        ----------
        parent      : QObject
                      Parent view for which the model in to be linked

        """
        Assertor.assert_data_types([parent], [QObject])
        super().__init__(parent)
        self.finn_data = {}
        self.parent.ui.push_button_hent_finn_data_1.clicked.connect(
            lambda: self.add_finn_info("_1"))
        self.parent.ui.push_button_finn_1.clicked.connect(
            lambda: self.open_finn_url("_1"))
        self.parent.ui.push_button_statistikk_1.clicked.connect(
            lambda: self.parent.statistics_view.add_statistics_info("_1"))

        self.parent.ui.push_button_hent_finn_data_2.clicked.connect(
            lambda: self.add_finn_info("_2"))
        self.parent.ui.push_button_finn_2.clicked.connect(
            lambda: self.open_finn_url("_2"))
        self.parent.ui.push_button_statistikk_2.clicked.connect(
            lambda: self.parent.statistics_view.add_statistics_info("_2"))

        self.parent.ui.push_button_hent_finn_data_3.clicked.connect(
            lambda: self.add_finn_info("_3"))
        self.parent.ui.push_button_finn_3.clicked.connect(
            lambda: self.open_finn_url("_3"))
        self.parent.ui.push_button_statistikk_3.clicked.connect(
            lambda: self.parent.statistics_view.add_statistics_info("_3"))
コード例 #6
0
    def __init__(self,
                 age: Union[int, float, str] = 0,
                 kinder_garden: str = '0',
                 sfo: str = '0',
                 student: str = '0'):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        age             : int, float, str
                          age of person
        kinder_garden   : str
                          kids in kinder garden, '1' true or '0' false
        sfo             : str
                          After school programme, '1' true or '0' false
        student         : str
                          Student classification, '1' true or '0' false

        """
        try:
            super().__init__('m', age, kinder_garden, sfo, student)
            Assertor.assert_data_types([age, kinder_garden, sfo, student],
                                       [(float, int, str), str, str, str])
        except Exception as male_exception:
            raise male_exception
コード例 #7
0
    def _assert_family_members(family_members: list):
        """
        Checking the family_members object. In this implementation a Family has the following
        characteristics:

        - Needs to be a list
        - Cannot be an empty list
        - All objects in the list must be either of class Male or Female
        - A family must have guardianship, i.e. have at least one person older than 17

        Parameters
        ----------
        family_members  : list
                          list of Male or Female objects

        """
        Assertor.assert_data_types([family_members], [list])

        if not family_members:
            raise ValueError("family_members cannot be empty, got '[]'")

        for family_member in family_members:
            Assertor.assert_data_types([family_member], [(Male, Female)])

        if all(int(family_member.alder) < 18 for family_member in family_members):
            raise NotPossibleError("no guardianship found, i.e. family must have at least "
                                   "one person older than 17 years.")
コード例 #8
0
    def __init__(self, community_json: dict):
        """
        Constructor / Instantiate the class.

        Parameters
        ----------
        community_json      : dict
                              JSON object as dict with community statistics

        """
        self.start_process()
        super().__init__(name=self.__class__.__name__)
        Assertor.assert_data_types([community_json], [dict])

        self.community_json = community_json

        self.input_operation(self.community_json)

        self.run_parallel([self.extract_1, self.extract_2, self.extract_3, self.extract_4,
                           self.extract_5, self.extract_6, self.extract_7])
        self.run_parallel([self.separate_1, self.separate_2, self.extract_8, self.separate_3,
                           self.separate_4, self.separate_5, self.separate_6])

        self.run_parallel([self.people_data_processing, self.family_data_processing,
                           self.environmental_process, self.transportation_process,
                           self.leisure_processing, self.shopping_process])

        self.multiplex()

        self.finn_community_statistics = self.output_operation()
        self.end_process()
コード例 #9
0
    def update(self, db_name: str, col_name: str, query: dict,
               new_value: dict):
        """
        method for updating document(s) in a collection

        Parameters
        ----------
        db_name     : str
                      db name to look for collection
        col_name    : str
                      collection name to apply update
        query       : dict
                      document to query
        new_value   : dict
                      new values to apply in document

        """
        try:
            LOGGER.info("trying to '{}' document '{}' with value '{}'".format(
                self.update.__name__, query, new_value))
            Assertor.assert_data_types([db_name, col_name], [str, str])

            collection = getattr(self._client,
                                 db_name.lower())[col_name.lower()]
            collection.update_many(query, new_value)

            LOGGER.success("'{}' successfully completed".format(
                self.update.__name__))
        except Exception as exp:
            LOGGER.exception(exp)
            raise exp
コード例 #10
0
    def delete(self, db_name: str, col_name: str):
        """
        Delete all documents in collection. Will also delete the db that the collection is in.

        Parameters
        ----------
        db_name     : str
                      name of db
        col_name    : str
                      name of collection to be deleted

        """
        try:
            LOGGER.info(
                "trying to '{}' all documents from collection: '{}' in db: '{}'"
                .format(self.delete.__name__, col_name, db_name))
            Assertor.assert_data_types([db_name, col_name], [str, str])

            collection = getattr(self._client, db_name)[col_name]
            count = collection.count()
            collection.drop()

            LOGGER.success(
                "'{}' successfully completed - '{}' document(s) deleted".
                format(self.delete.__name__, count))
        except Exception as exp:
            LOGGER.exception(exp)
            raise exp
コード例 #11
0
    def read(self, db_name: str, col_name: str):
        """
        method for reading all documents in a collection

        Parameters
        ----------
        db_name     : str
                      db name to lookup
        col_name    : str
                      collection name to lookup

        Returns
        -------
        out         : list
                      all documents in collection

        """
        try:
            LOGGER.info(
                "trying to '{}' all documents in collection: '{}' from db: '{}'"
                .format(self.read.__name__, col_name, db_name))
            Assertor.assert_data_types([db_name, col_name], [str, str])

            documents = []
            for document in getattr(self._client[db_name.lower()],
                                    col_name.lower()).find():
                documents.append(document)

            LOGGER.success(
                "'{}' successfully completed - '{}' document(s) found".format(
                    self.read.__name__, len(documents)))
            return documents
        except Exception as exp:
            LOGGER.exception(exp)
            raise exp
コード例 #12
0
    def __init__(self, family_members: list = None, income: Union[int, float, str] = 0,
                 cars: Union[int, str] = 0):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        family_members  : list
                          list of Person (Male or Female) instances
        income          : int, float, str
                          gross yearly income
        cars            : int, str
                          number of cars in the family

        """
        super().__init__()
        try:
            self._assert_family_members(family_members)
            Assertor.assert_data_types([income, cars], [(int, float, str), (int, str)])
            Assertor.assert_non_negative([income, cars])

            self._family_members = family_members
            self._inntekt = str(income)
            self._antall_biler = str(cars)
            LOGGER.success(
                "created '{}', with id: [{}]".format(self.__class__.__name__, self.id_str))
        except Exception as family_exception:
            LOGGER.exception(family_exception)
            raise family_exception
コード例 #13
0
    def __init__(self,
                 age: Union[int, float, str] = 0,
                 kinder_garden: str = '0',
                 sfo: str = '0',
                 pregnant: str = '0'):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        age             : int, float, str
                          age of person
        kinder_garden   : str
                          kids in kinder garden, '1' true or '0' false
        sfo             : str
                          After school programme, '1' true or '0' false
        pregnant        : str
                          Pregnant female, '1' true or '0' false

        """
        try:
            super().__init__('k', age, kinder_garden, sfo)
            Assertor.assert_data_types([age, kinder_garden, sfo],
                                       [(float, int, str), str, str])
            Assertor.assert_arguments({pregnant: ['pregnant', ('0', '1')]})

            if Person.sifo_age(age) not in ('19', '50') and pregnant == '1':
                raise ValueError("pregnancy at this age is not possible")

            self._gravid = pregnant
            LOGGER.success("created '{}', with id: [{}]".format(
                self.__class__.__name__, self.id_str))
        except Exception as female_exception:
            LOGGER.exception(female_exception)
            raise female_exception
コード例 #14
0
ファイル: finn_stat.py プロジェクト: seemir/stressa
    def extract_images(self, detail_statistics: dict, info: dict):
        """
        method for extracting image node from detail statistics JSON

        Parameters
        ----------
        detail_statistics   : dict
                              dictionary with statistics info
        info                : dict
                              info dictionary with results

        """
        Assertor.assert_data_types([detail_statistics, info], [dict, dict])
        for prop, value in detail_statistics.items():
            if prop.lower() == 'props':
                for pro, val in value.items():
                    if pro.lower() == 'pageprops':
                        for pr_name, vl_name in val.items():
                            if pr_name.lower() == 'ad':
                                for sub_prop, sub_val in vl_name.items():
                                    if sub_prop.lower() == 'content':
                                        for sub_pr, sub_vl in sub_val.items():
                                            if sub_pr == 'images':
                                                info.update({'images': sub_vl})
        return info
コード例 #15
0
ファイル: finn_stat.py プロジェクト: seemir/stressa
    def extract_sqm_price(self, sql_price_statistics: dict, info: dict):
        """
        method for extracting square meter price

        Parameters
        ----------
        sql_price_statistics : dict
                               dictionary with square meter price
        info                 : dict
                               dictionary to store results

        """
        Assertor.assert_data_types([sql_price_statistics, info], [dict, dict])
        for prop, value in sql_price_statistics.items():
            if prop.lower() == 'props':
                for pro, val in value.items():
                    if pro.lower() == 'pageprops':
                        for pr_name, vl_name in val.items():
                            if pr_name.lower() == 'areasales':
                                for name, inf in vl_name.items():
                                    if isinstance(
                                            inf,
                                        (int,
                                         float)) and name.lower() == 'price':
                                        info.update({
                                            'sqm_price':
                                            Amount(str(inf)).amount + " kr/m²"
                                        })
        return info
コード例 #16
0
ファイル: finn_stat.py プロジェクト: seemir/stressa
    def extract_view_statistics(self, total_view_statistics: dict, info: dict):
        """
        method for extracting the total view statistics

        Parameters
        ----------
        total_view_statistics   : dict
                                  dictionary with view statistics
        info                    : dict
                                  dictionary to store results

        Returns
        -------
        out                     : dict
                                  dictionary with results

        """
        Assertor.assert_data_types([total_view_statistics, info], [dict, dict])
        for prop, value in total_view_statistics.items():
            if prop.lower() == 'props':
                for pro, val in value.items():
                    if pro.lower() == 'pageprops':
                        for pr_name, vl_name in val.items():
                            if isinstance(
                                    vl_name,
                                (int,
                                 float)) and pr_name.lower() == 'totalclicks':
                                info.update(
                                    {"views": Amount(str(vl_name)).amount})
        return info
コード例 #17
0
    def __init__(self, parent: QWidget):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        parent      : QObject
                      parent class for which this dialog window is part

        """
        Assertor.assert_data_types([parent], [QWidget])
        super().__init__(parent)
        self._parent = parent
        self.ui = loadUi(os.path.join(os.path.dirname(__file__), "forms/budget_form.ui"), self)
        self.ui.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.ui.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        self.ui.label_note_1.setFont(QFont('MS Shell Dlg 2', 7))
        self.ui.label_note_2.setFont(QFont('MS Shell Dlg 2', 7))

        self._error_view = self.parent.error_view
        self._meta_view = MetaView(self)

        self._budget_model = BudgetModel(self)

        self.ui.push_button_exporter_1.clicked.connect(self.export)
        self.ui.push_button_tom_skjema_1.clicked.connect(self.clear_all)
        self.ui.push_button_budget_meta_data_1.clicked.connect(self.meta_view.display)
        self.ui.push_button_avbryt_1.clicked.connect(self.close)
コード例 #18
0
ファイル: statistics_model.py プロジェクト: seemir/stressa
    def clear_statistics_info(self, postfix: str):
        """
        method for clearing finn statistics from line_edit

        Parameters
        ----------
        postfix     : str
                      index if used in naming of line_edits

        """
        Assertor.assert_data_types([postfix], [str])
        grandparent = self.parent.parent.finn_model
        for key in self._statistics_keys:
            full_key = key + postfix
            if full_key in self.data.keys():
                self.data.pop(full_key)
            if full_key in grandparent.data.keys():
                grandparent.data.pop(full_key)
            if full_key in grandparent.finn_data.keys():
                grandparent.finn_data.pop(full_key)

            if key == "city_area":
                self.parent.label_city_area_sqm_price.setText("KMP (område)")
                self.parent.label_sales_city_area.setText("Salg (område)")
            elif key == "municipality":
                self.parent.label_municipality_sqm_price.setText(
                    "KMP (kommune)")
                self.parent.label_sales_municipality.setText("Salg (kommune)")
            elif key in self._ignore_clear_keys:
                continue
            else:
                getattr(self.parent.ui, "line_edit_" + key).clear()
            self.clear_charts()
コード例 #19
0
ファイル: chart.py プロジェクト: seemir/stressa
    def create_bins(x: list, y: list, bins: list):
        """
        method for creating bins for bar char

        Parameters
        ----------
        x       : list
                  x-values
        y       : list
                  y-value
        bins    : list
                  bins

        Returns
        -------
        out     : np.ndarray
                  bins for bar chart

        """
        Assertor.assert_data_types([x, y, bins], [list, list, list])
        bin_array = []
        for i, value in enumerate(x):
            if y[i] != 0:
                bin_array.append([value] * y[i])
            else:
                bin_array.append([0])
        return np.histogram(list(chain(*bin_array)), bins=bins)
コード例 #20
0
ファイル: share.py プロジェクト: seemir/stressa
    def __init__(self,
                 numerator: Union[Decimal, Money],
                 denominator: Union[Decimal, Money] = None):
        """
        Constructor / instantiation

        Parameters
        ----------
        numerator   : Decimal, Money
                      numerator of the share object
        denominator : Decimal, Money
                      denominator of the share object

        """
        try:
            Assertor.assert_data_types([numerator, denominator],
                                       [(Decimal, Money),
                                        (Decimal, Money, type(None))])
            super().__init__()
            self._numerator = numerator
            self._denominator = denominator
            self._percent = Percent(
                numerator / denominator) if self.denominator else Percent("0")
            self._value = self._percent.value
        except Exception as share_error:
            raise share_error
コード例 #21
0
ファイル: skatteetaten.py プロジェクト: seemir/stressa
    def __init__(self, age: Union[str, int], income: Union[str, int, float]):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        age         : str, int
                      age of individual
        income      : str, int, float
                      income of individual

        """

        try:
            super().__init__()
            Assertor.assert_data_types([age, income], [(str, int),
                                                       (str, int, float)])

            self.age = str(age + 1)
            self.income = str(income)
            self.year = str(2022)
            self.url = SKATTEETATEN_URL + self.year

            LOGGER.success("created '{}', with id: [{}]".format(
                self.__class__.__name__, self.id_))
        except Exception as skatteetaten_exception:
            LOGGER.exception(skatteetaten_exception)
            raise skatteetaten_exception
コード例 #22
0
    def __init__(self, parent: QWidget):
        """
        Constructor / Instantiation of class

        Parameters
        ----------
        parent  : QWidget
                  parent view for the SifoView

        """
        Assertor.assert_data_types([parent], [QWidget])
        super().__init__(parent=parent)
        self.ui = loadUi(os.path.join(os.path.dirname(__file__), "forms/sifo_form.ui"), self)
        self.ui.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.ui.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        self.ui.setWindowFlag(Qt.WindowContextHelpButtonHint, False)

        self._parent = parent
        self._sifo_model = SifoModel(self)
        self._error_view = self.parent.error_view
        self._meta_view = MetaView(self)

        self.ui.push_button_sifo_meta_data.clicked.connect(self.meta_view.display)
        self.ui.push_button_vis_resultatet.clicked.connect(self.sifo_model.calculate_sifo_expenses)
        self.ui.push_button_tom_skjema_1.clicked.connect(self.clear_all)
        self.ui.push_button_avbryt_1.clicked.connect(self.close)
        self.ui.push_button_tom_skjema_2.clicked.connect(self.clear_all)
        self.ui.push_button_avbryt_2.clicked.connect(self.close)
        self.ui.push_button_tilbake.clicked.connect(self.back)
        self.ui.push_button_eksporter.clicked.connect(self.export)
コード例 #23
0
ファイル: statistics_view.py プロジェクト: seemir/stressa
    def __init__(self, parent: QWidget):
        """
        Constructor / Instantiation of class

        Parameters
        ----------
        parent  : QWidget
                  parent view for the SifoView

        """
        Assertor.assert_data_types([parent], [QWidget])
        super().__init__(parent=parent)
        self.ui = loadUi(
            os.path.join(os.path.dirname(__file__),
                         "forms/statistics_form.ui"), self)
        self.ui.setWindowFlag(Qt.WindowMinimizeButtonHint, True)
        self.ui.setWindowFlag(Qt.WindowMaximizeButtonHint, True)
        self.ui.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self._parent = parent
        self._statistics_model = StatisticsModel(self)
        self._meta_view = MetaView(self)
        self._map_view = MapView(self)
        self._images_view = ImagesView(self)

        self.ui.push_button_meta_data.clicked.connect(self.meta_view.display)
        self.ui.push_button_oppdater.clicked.connect(self.update)
        self.ui.push_button_show_in_map_1.clicked.connect(self.map_view.show)
        self.ui.push_button_show_in_map_2.clicked.connect(self.map_view.show)
        self.ui.push_button_show_in_map_3.clicked.connect(self.map_view.show)
        self.ui.push_button_show_in_map_4.clicked.connect(self.map_view.show)
        self.ui.push_button_show_in_map_5.clicked.connect(self.map_view.show)
        self.ui.push_button_show_in_map_6.clicked.connect(self.map_view.show)

        self.ui.push_button_images.clicked.connect(self.images_view.show)
コード例 #24
0
ファイル: ssb_payload.py プロジェクト: seemir/stressa
    def sektor(self, sekt: list):
        """
        sektor setter

        """
        Assertor.assert_data_types([sekt], [list])
        Assertor.assert_arguments([sekt], [{"sektor": (["04b"], ["04a"])}])
        self._sektor = sekt
コード例 #25
0
    def add_signal(self, signal: Signal, key: str):
        """
        method for adding signal to workflow

        """
        Assertor.assert_data_types([signal, key], [Signal, str])
        self.signal.update({key: signal})
        self.add_node(signal)
コード例 #26
0
ファイル: test_assertor.py プロジェクト: yanzj/stressa
    def test_assert_data_types(correct_data_types):
        """
        Test that assert_data_types() method raises TypeError if first
        argument is not of correct data_type.

        """
        invalid_arg = 90210
        with pt.raises(TypeError):
            Assertor.assert_data_types([invalid_arg], [correct_data_types])
コード例 #27
0
    def to_json(self, file_dir: str = "report/json/finn_information"):
        """
        save statistics information to JSON file

        """
        Assertor.assert_data_types([file_dir], [str])
        self.save_json(self.community_stat_information(), file_dir,
                       file_prefix="CommunityStatInfo_")
        LOGGER.success(
            "'community_stat_information' successfully parsed to JSON at '{}'".format(file_dir))
コード例 #28
0
    def payload(self, pay_load: SsbPayload = None):
        """
        Payload setter

        Parameters
        ----------
        pay_load      : SsbPayload
                        new payload to be set

        """
        Assertor.assert_data_types([pay_load], [(type(None), SsbPayload)])
        self._payload = pay_load
コード例 #29
0
ファイル: person.py プロジェクト: yanzj/stressa
    def alder(self, age: Union[int, float, str]):
        """
        age setter

        Parameters
        ----------
        age     : int, float, str
                  new age to be set

        """
        Assertor.assert_data_types([age], [(float, int, str)])
        self._alder = self.sifo_age(age)
コード例 #30
0
ファイル: finn_stat.py プロジェクト: seemir/stressa
    def __init__(self, finn_code: str):
        """
        Constructor / Instantiate the class

        Parameters
        ----------
        finn_code   : str
                      Finn-code to search finn statistics for

        """
        Assertor.assert_data_types([finn_code], [str])
        super().__init__(finn_code=finn_code)