def _validate_args(mdb, dp, si):
    driver = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())

    dataSource = driver.Open(dp, GA_ReadOnly)
    if not dataSource:
        raise utils.ValidationException(
            "Not a valid shape file (%s) provided for parameter --dp." % dp)
    else:
        dataSource.Destroy()

    try:
        if not os.path.dirname(mdb):
            mdb = os.path.join(os.getcwd(), mdb)

        conn = pyodbc.connect(utils.MS_ACCESS_CONNECTION % mdb)
        conn.close()
    except pyodbc.Error as ex:
        raise utils.ValidationException(ex.message)

    dataSource = gdal.Open(si, GA_ReadOnly)
    if not dataSource:
        raise utils.ValidationException(
            "File open error. Not a valid file (%s) provided for the '--si' parameter."
            % si)

    else:
        dataSource = None
Example #2
0
def _validate_args(net, sca, ad8, sac, spe):
    driver_shp = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())
    try:
        dataSource = driver_shp.Open(net, 1)
        if not dataSource:
            raise utils.ValidationException(
                "Not a valid shape file (%s) provided for the '--net' parameter."
                % net)
        else:
            dataSource.Destroy()
    except Exception as ex:
        raise utils.ValidationException(ex.message)

    try:
        if not ad8 and not sca:
            raise utils.ValidationException(
                "One of the 2 parameters '--ad8' or '--sca' must be specified."
            )

        if ad8 and sca:
            raise utils.ValidationException(
                "Only one of the 2 parameters '--ad8' or '--sca' needs to be specified."
            )

        if sca:
            dataSource = gdal.Open(sca, GA_ReadOnly)
            if not dataSource:
                raise utils.ValidationException(
                    "File open error. Not a valid file (%s) provided for the '--sca' "
                    "parameter." % sca)
            else:
                dataSource = None

        if ad8:
            dataSource = gdal.Open(ad8, GA_ReadOnly)
            if not dataSource:
                raise utils.ValidationException(
                    "File open error. Not a valid file (%s) provided for '--ad8' "
                    "parameter." % ad8)
            else:
                dataSource = None

        dataSource = gdal.Open(sac, GA_ReadOnly)
        if not dataSource:
            raise utils.ValidationException(
                "File open error. Not a valid file (%s) provided for '--sac' parameter."
                % sac)
        else:
            dataSource = None
    except Exception as ex:
        raise utils.ValidationException(ex.message)

    spe_dir = os.path.dirname(os.path.abspath(spe))
    if not os.path.exists(spe_dir):
        raise utils.ValidationException(
            "File path '(%s)' for output file (parameter '--spe') does not exist."
            % spe_dir)
Example #3
0
def _validate_args(mdb, high_esi, medium_esi, low_esi, alpha):
    try:
        if not os.path.dirname(mdb):
            mdb = os.path.join(os.getcwd(), mdb)

        conn = pyodbc.connect(utils.MS_ACCESS_CONNECTION % mdb)
        conn.close()
    except pyodbc.Error as ex:
        raise utils.ValidationException(ex.message)

    err_msg = "Invalid value found for the parameter '{}'. Value must be greater than zero"
    if high_esi <= 0:
        raise utils.ValidationException(err_msg.format('--high-esi'))
    if medium_esi <= 0:
        raise utils.ValidationException(err_msg.format('--medium-esi'))
    if low_esi <= 0:
        raise utils.ValidationException(err_msg.format('--low-esi'))

    err_msg = "Invalid value found for the parameter '{}'."
    if high_esi != max(high_esi, medium_esi, low_esi):
        raise utils.ValidationException(
            err_msg.format('--high-esi') +
            " The specified value is not the highest value.")

    if low_esi != min(high_esi, medium_esi, low_esi):
        raise utils.ValidationException(
            err_msg.format('--low-esi') +
            " The specified value is not the lowest value.")

    if alpha <= 0:
        raise utils.ValidationException(
            "Invalid value found for parameter '--alpha.'. Value must be more than zero."
        )
Example #4
0
def _validate_args(dp, rd, z, mdb, dpsi):
    # DEBUG:
    print("Validating inputs...")
    driver = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())
    try:
        dataSource = driver.Open(dp, GA_ReadOnly)
        if not dataSource:
            raise utils.ValidationException(
                "Not a valid shapefile (%s) provided for parameter --dp." % dp)
        else:
            dataSource.Destroy()
    except Exception as e:
        msg = "Failed to open the shapefile (%s) provided for parameter --dp. " % dp + e.message
        raise utils.ValidationException(msg)

    try:
        dataSource = driver.Open(rd, GA_ReadOnly)
        if not dataSource:
            raise utils.ValidationException(
                "Not a valid shapefile (%s) provided for parameter --rd." % rd)
        else:
            dataSource.Destroy()
    except Exception as e:
        msg = "Failed to open the shapefile (%s) provided for parameter --rd. " % rd + e.message
        raise utils.ValidationException(msg)

    dpsi_dir = os.path.dirname(os.path.abspath(dpsi))
    if not os.path.exists(dpsi_dir):
        raise utils.ValidationException(
            "File path '(%s)' for output file (parameter --dpsi) does not exist."
            % dpsi_dir)
    try:
        if not os.path.dirname(mdb):
            mdb = os.path.join(os.getcwd(), mdb)

        conn = pyodbc.connect(utils.MS_ACCESS_CONNECTION % mdb)
        conn.close()
    except pyodbc.Error as ex:
        raise utils.ValidationException(ex.message)

    try:
        dem = gdal.Open(z)
        dem = None
    except Exception as ex:
        raise utils.ValidationException(ex.message)

    # DEBUG:
    print("Finished validating inputs...")
Example #5
0
    def verify_payment_status(self, paymentSessionId):
        """tells if the payment was successful or not, returns tuple (success, whole response)"""

        cmd = dict(eshopGoId=settings.GOPAY_ESHOP_GOID,
                   paymentSessionId=paymentSessionId)
        concat_cmd = self.concat(utils.Concat.PAYMENT_STATUS, cmd)
        cmd['encryptedSignature'] = self.crypt.encrypt(concat_cmd)
        cmd = utils.prefix_command_keys(cmd,
                                        prefix=const.PREFIX_CMD_PAYMENT_RESULT)
        r = requests.post(const.GOPAY_PAYMENT_STATUS_URL,
                          data=cmd,
                          verify=VERIFY_SSL)
        #        print r.content
        if r.status_code != 200:
            raise utils.ValidationException(WRONG_STATUS_MSG % r.status_code)
        utils.CommandsValidator(r.content).payment_status()
        response = utils.parse_xml_to_dict(r.content)
        #        print response
        return response['sessionState'] == const.PAYMENT_DONE, response
Example #6
0
    def create_payment(self,
                       productName,
                       variableSymbol,
                       totalPriceInCents,
                       paymentChannels=const.PAYMENT_METHODS):
        cmd = self._create_payment_cmd(productName, variableSymbol,
                                       totalPriceInCents, paymentChannels)
        payment_string = self.concat(utils.Concat.PAYMENT, cmd)
        cmd['encryptedSignature'] = self.crypt.encrypt(payment_string)
        cmd = utils.prefix_command_keys(cmd, const.PREFIX_CMD_PAYMENT)
        r = requests.post(const.GOPAY_NEW_PAYMENT_URL,
                          data=cmd,
                          verify=VERIFY_SSL)

        if r.status_code != 200:
            raise utils.ValidationException(WRONG_STATUS_MSG % r.status_code)
        utils.CommandsValidator(r.content).payment()

        response = utils.parse_xml_to_dict(r.content)
        #        print response
        return response['paymentSessionId']
Example #7
0
def _compute_direct_stream_sediment(net):
    # ref to seddirstream c++ function for the logic of this function
    """
    Computes 'SedDir" and 'SpecSedDir' and appends these 2 fields to the stream network shapefile

    :param net: stream network shapefile
    :return: None
    """

    driver = ogr.GetDriverByName(utils.GDALFileDriver.ShapeFile())
    dataSource = driver.Open(net, 1)
    layer = dataSource.GetLayer()
    layerDefn = layer.GetLayerDefn()

    # put area in m^2 to km^2 by multiplying 10^6 and then put weight in kg to Mg by dividing 10^3
    KG_PER_SQUARE_METER_TO_MG_PER_SQUARE_KM_FACTOR = 1000

    try:
        # delete field "SedDir" if it exists
        fld_index = layerDefn.GetFieldIndex('SedDir')
        if fld_index > 0:
            layer.DeleteField(fld_index)

        # delete "SpecSedDir" if it exists
        fld_index = layerDefn.GetFieldIndex('SpecSedDir')
        if fld_index > 0:
            layer.DeleteField(fld_index)

        # check the following fields exist
        fld_index_sed_accum = layerDefn.GetFieldIndex('SedAccum')
        fld_index_spec_sed = layerDefn.GetFieldIndex('SpecSed')
        fld_index_link_no = layerDefn.GetFieldIndex('LINKNO')
        fld_index_us_link_no1 = layerDefn.GetFieldIndex('USLINKNO1')
        fld_index_us_link_no2 = layerDefn.GetFieldIndex('USLINKNO2')
        fld_index_cont_area = layerDefn.GetFieldIndex('DSContArea')

        if any(index == -1 for index in [
                fld_index_sed_accum, fld_index_spec_sed, fld_index_link_no,
                fld_index_us_link_no1, fld_index_us_link_no2,
                fld_index_cont_area
        ]):
            raise Exception("Invalid stream network shapefile.")

    except Exception as ex:
        raise utils.ValidationException(ex.message)

    # add a new field (column) 'SedDir' to the attribute table
    layer.CreateField(ogr.FieldDefn('SedDir', ogr.OFTReal))
    fld_index_sed_dir = layerDefn.GetFieldIndex('SedDir')

    # add a new field (column) 'SpecSedDir' to the attribute table
    layer.CreateField(ogr.FieldDefn('SpecSedDir', ogr.OFTReal))
    fld_index_spec_sed_dir = layerDefn.GetFieldIndex('SpecSedDir')

    # list objects to store shape file data
    links = []
    up1_links = []
    up2_links = []
    sed_accums = []
    ds_areas = []

    # populate the list objects
    for feature in layer:
        links.append(feature.GetField(fld_index_link_no))
        up1_links.append(
            feature.GetField(fld_index_us_link_no1)
            if feature.GetField(fld_index_us_link_no1) > 0 else 0)
        up2_links.append(
            feature.GetField(fld_index_us_link_no2)
            if feature.GetField(fld_index_us_link_no2) > 0 else 0)
        sed_accums.append(feature.GetField(fld_index_sed_accum))
        ds_areas.append(feature.GetField(fld_index_cont_area))

    list_index = 0
    sac_dir = 0
    dir_area = 0
    link_sed_accum = 0
    link_ds_area = 0

    layer.ResetReading()
    for feature in layer:

        try:

            def _get_upstream_sed_accum_and_area(link_no, links, sed_accums,
                                                 ds_areas):
                if link_no == 0:
                    return 0, 0

                for i in range(0, len(links)):
                    if links[i] == link_no:
                        return sed_accums[i], ds_areas[i]

                return 0, 0

            link_sed_accum = 0
            if up1_links[list_index] == 0 and up2_links[list_index] == 0:
                # get the sedaccum and dsarea for the link
                link_sed_accum = sed_accums[list_index]
                sac_dir = link_sed_accum
                dir_area = ds_areas[list_index]

            elif up1_links[list_index] == 0 and up2_links[list_index] > 0:
                # get the sedaccum and dsarea for the link
                link_sed_accum = sed_accums[list_index]
                link_ds_area = ds_areas[list_index]

                # get the sedaccum and dsarea for the link upstream 2
                link_up2_sed_accum, link_up2_ds_area = _get_upstream_sed_accum_and_area(
                    up2_links[list_index], links, sed_accums, ds_areas)

                sac_dir = link_sed_accum - link_up2_sed_accum
                dir_area = link_ds_area - link_up2_ds_area

            else:
                # get the sedaccum and dsarea for the link
                link_sed_accum = sed_accums[list_index]
                link_ds_area = ds_areas[list_index]

                # get the sedaccum and dsarea for the link upstream 1
                link_up1_sed_accum, link_up1_ds_area = _get_upstream_sed_accum_and_area(
                    up1_links[list_index], links, sed_accums, ds_areas)

                # get the sedaccum and dsarea for the link upstream 2
                link_up2_sed_accum, link_up2_ds_area = _get_upstream_sed_accum_and_area(
                    up2_links[list_index], links, sed_accums, ds_areas)

                sac_dir = link_sed_accum - link_up1_sed_accum - link_up2_sed_accum
                dir_area = link_ds_area - link_up1_ds_area - link_up2_ds_area

            # due to rounding any dir sed accum that is too small, set those to zero
            if abs(sac_dir) < link_sed_accum * pow(10, -6):
                sac_dir = 0

            # write dir sed accum to stream network shapefile
            feature.SetField(fld_index_sed_dir, sac_dir)
            specific_sed_accum = (
                sac_dir /
                dir_area) * KG_PER_SQUARE_METER_TO_MG_PER_SQUARE_KM_FACTOR

            # write specific dir sed accum to stream network shapefile
            feature.SetField(fld_index_spec_sed_dir, specific_sed_accum)

            # rewrite the feature to the layer - this will in fact save the data to the file
            layer.SetFeature(feature)
            list_index += 1
            #_show_progress()
        except:
            dataSource.Destroy()
            raise

    # close datasource
    dataSource.Destroy()