Example #1
0
async def run(env, username, password):
    because = Because("concurrent", env)
    transfer = because.login(username, password)
    print("Waiting...")
    token = await transfer
    print("Token:")
    print(token.pretty_text(u"  "))
Example #2
0
def main():
    args = get_args("Get a token.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    transfer = because.login(args.username, args.password)
    print("Waiting...")
    transfer.wait()
    print("Token:")
    print(because.token.pretty_text(u"  "))
Example #3
0
 def __init__(self, parent, client, iface):
     super(BasemapsDialog, self).__init__(
         parent=parent,
         iface=iface,
         client=client,
         title="Because Basemaps",
         uiPath=os.path.join(HERE, "basemaps.ui"),
     )
     self.because = Because("qt", env="dev")
     self.basemaps_dict = None
def main():
    args = get_args("Reverse geocode a location.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    because.login(args.username, args.password).wait()

    x, y = (-76.981041, 38.878649)
    matches = because.reverse_geocode(x, y, service="mapbox").wait()
    for index, match in enumerate(matches):
        print("Match {}:".format(index))
        print("""
            Score: {}
            Location: ({}, {})
            Address: {}
            """.format(match.score, match.x, match.y, match.address))
Example #5
0
def main():
    args = get_args("Get a route.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    because.login(args.username, args.password).wait()

    home = "3637 Far West Blvd, Austin, TX 78731"
    dest = "1600 Pennsylvania Ave., Washington, DC"
    route = because.route(home, dest, service="mapbox").wait()

    for leg_number, leg in enumerate(route.legs()):
        print("Leg {}:".format(leg_number))
        for step_number, step in enumerate(leg.steps()):
            print("Step {}:".format(leg_number))
            print(step.instructions)
            print(step.points)
Example #6
0
def main():
    args = get_args("Geocode an address.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    because.login(args.username, args.password).wait()

    address = "1600 Pennsylvania Ave., Washington, DC"
    matches = because.geocode(address, service="mapbox").wait()
    for index, match in enumerate(matches):
        print("Match {}:".format(index))
        print(
            """
            Score: {}
            Location: ({}, {})
            Address: {}
            """.format(match.score, match.x, match.y, match.address), )
Example #7
0
    def __init__(self):
        super(Window, self).__init__()

        # Set a title and comfortable minimum size for the window.
        self.setWindowTitle("Because Qt Demo")
        self.setMinimumWidth(1024)
        self.setMinimumHeight(768)

        # Create boxes allowing a username and password to be put in.
        self.usernameLabel = QLabel("Email", self)
        self.usernameInput = QLineEdit(self)
        self.usernameInput.setPlaceholderText("*****@*****.**")
        self.usernameInput.setFocus()

        self.passwordLabel = QLabel("Password")
        self.passwordInput = QLineEdit(self)
        self.passwordInput.setPlaceholderText("myConnectPassword")
        self.passwordInput.setEchoMode(QLineEdit.PasswordEchoOnEdit)

        # Create a button for triggering the login process.
        self.loginButton = QPushButton("Login", self)
        self.loginButton.clicked.connect(self.login)
        self.passwordInput.returnPressed.connect(self.loginButton.click)

        # Create an area to display text in.
        self.output = QTextEdit(self)
        self.output.setReadOnly(True)

        # Lay everything out inside the window vertically.
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.usernameLabel)
        self.layout.addWidget(self.usernameInput)
        self.layout.addWidget(self.passwordLabel)
        self.layout.addWidget(self.passwordInput)
        self.layout.addWidget(self.loginButton)
        self.layout.addWidget(self.output)

        # Get a 'because' object. Note that the string "qt" is passed.
        # This asks because to use its qt interface/implementation
        self.because = Because("qt", "dev")
Example #8
0
def main():
    args = get_args("Get a list of basemaps.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    because.login(args.username, args.password).wait()

    basemaps = because.basemaps().wait()
    for basemap in basemaps.values():
        print("Basemap {}: {}".format(basemap.title, basemap.url))

    basemap = because.basemap(u"Boundless Basemap").wait()
    print("Basemap {}: {}".format(basemap.title, basemap.url))
Example #9
0
def main():
    args = get_args("Do some searches.")
    log = configure_logging(debug=args.debug)
    because = Because(env=args.env, log=log)
    because.login(args.username, args.password).wait()

    categories = because.search_categories().wait()
    for key, category in categories.items():
        print("Category {}: {}".format(category.key, category.description))

    results = because.search_category("DOC", "geoserver").wait()
    for index, result in enumerate(results, 1):
        print("Result {}: {}".format(index, result.title))
        print("    {}".format(result.url))
        print()

    results = because.opensearch("geoserver").wait()
    for index, result in enumerate(results, 1):
        print("Result {}: {}".format(index, result.title))
        print("    {}".format(result.url))
        print()
Example #10
0
class BasemapsDialog(Dialog):
    """Example dialog for use of Boundless basemaps service via because
    """
    def __init__(self, parent, client, iface):
        super(BasemapsDialog, self).__init__(
            parent=parent,
            iface=iface,
            client=client,
            title="Because Basemaps",
            uiPath=os.path.join(HERE, "basemaps.ui"),
        )
        self.because = Because("qt", env="dev")
        self.basemaps_dict = None

    def init(self):
        self.populateButton.clicked.connect(self.populate)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def populate(self):
        if not self.basemaps_dict:
            # TODO: stop blocking. have to expose signals via Result. :/
            self.because.login("myusername", "mypassword").wait()
            self.basemaps_dict = self.because.basemaps().wait()

        self.basemapComboBox.clear()
        basemaps = sorted(self.basemaps_dict.values(), key=lambda m: m.title)
        for basemap in basemaps:
            if basemap.title == "Recent Imagery":
                continue
            if basemap.standard != "XYZ" or basemap.tile_format != "PNG":
                continue
            print(basemap.pretty_text())
            self.basemapComboBox.addItem(basemap.title)

    def accept(self):
        # TODO use the selected basemap
        chosen_basemap = str(self.basemapComboBox.currentText())
        if not chosen_basemap:
            QMessageBox.warning(self, "More input needed to continue",
                                "Please populate the basemaps list first")
            return

        basemap = self.basemaps_dict.get(chosen_basemap.lower())

        api_key = self.apiKeyInput.text()
        if not api_key:
            QMessageBox.warning(self, "More input needed to continue",
                                "Please enter an API key")
            return
        # In case newlines are pasted in, accidental invisible whitespace, etc.
        api_key = api_key.strip()

        # TODO: find instances of {-?} and flag them somewhere else where $ is
        # added.

        # TODO: ensure dollar signs to generate the URL, in the basemap impl
        # url = "http://api.dev.boundlessgeo.io/v1/basemaps/mapbox/streets/${z}/${x}/${y}.png"
        # url = "http://api.dev.boundlessgeo.io/v1/basemaps/boundless/osm/${x}/${y}/${z}.png"
        url = basemap.url
        if "{-" in url:
            url = url.replace("{-", "{")
            y_origin = "bottom"
        url = url.replace("{", "${")

        # TODO: do this in the endpoint instead!
        suffix = "?apikey={}".format(api_key)
        url = url + suffix
        print("url={0!r}".format(url))

        # TODO: use a method on the frontend
        #   which uses the service definition, as a first cut
        #   then dynamically construct endpoint instance to use

        layer = GDALBasemapLayer(url,
                                 basemap.title,
                                 "Because",
                                 y_origin=y_origin)
        registry = QgsMapLayerRegistry.instance()
        registry.addMapLayer(layer)

        self.hide()
Example #11
0
class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        # Set a title and comfortable minimum size for the window.
        self.setWindowTitle("Because Qt Demo")
        self.setMinimumWidth(1024)
        self.setMinimumHeight(768)

        # Create boxes allowing a username and password to be put in.
        self.usernameLabel = QLabel("Email", self)
        self.usernameInput = QLineEdit(self)
        self.usernameInput.setPlaceholderText("*****@*****.**")
        self.usernameInput.setFocus()

        self.passwordLabel = QLabel("Password")
        self.passwordInput = QLineEdit(self)
        self.passwordInput.setPlaceholderText("myConnectPassword")
        self.passwordInput.setEchoMode(QLineEdit.PasswordEchoOnEdit)

        # Create a button for triggering the login process.
        self.loginButton = QPushButton("Login", self)
        self.loginButton.clicked.connect(self.login)
        self.passwordInput.returnPressed.connect(self.loginButton.click)

        # Create an area to display text in.
        self.output = QTextEdit(self)
        self.output.setReadOnly(True)

        # Lay everything out inside the window vertically.
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.usernameLabel)
        self.layout.addWidget(self.usernameInput)
        self.layout.addWidget(self.passwordLabel)
        self.layout.addWidget(self.passwordInput)
        self.layout.addWidget(self.loginButton)
        self.layout.addWidget(self.output)

        # Get a 'because' object. Note that the string "qt" is passed.
        # This asks because to use its qt interface/implementation
        self.because = Because("qt", "dev")

    def login(self):
        # Retrieve text and do very basic validation on it before proceeding
        username = self.usernameInput.text().strip()
        password = self.passwordInput.text().strip()
        if not username or not password:
            self.output.clear()
            self.output.append("Please provide both username and password!")
            return

        # Disable the button so the user doesn't spam it by accident
        self.loginButton.setEnabled(False)

        # Use because to login
        transfer = self.because.login(username, password)
        self.output.append(
            "Transfer started at {}".format(transfer.started_at)
        )

        # When using the Qt interface, the transfer object has signals
        # that you can connect slots to.
        transfer.signals.success.connect(self.showToken)
        transfer.signals.failure.connect(self.beSad)
        transfer.signals.uploadProgress.connect(self.showUploadProgress)
        transfer.signals.downloadProgress.connect(self.showDownloadProgress)

        # Hang on to this so we can play with it later
        self.transfer = transfer

        # Don't transfer.wait() because that blocks, freezing the thread!
        # Let the signals take care of it asynchronously.

    def showUploadProgress(self, count, total):
        """Demonstrate how to handle uploadProgress.

        This signal is forwarded from QNetworkReply.
        """
        self.output.append("Upload: {}/{}".format(count, total))

    def showDownloadProgress(self, count, total):
        """Demonstrate how to handle downloadProgress.

        This signal is forwarded from QNetworkReply.
        """
        self.output.append("Upload: {}/{}".format(count, total))

    def showToken(self):
        """Called when login succeeds.
        """
        # You wouldn't normally grab the token like this. It's stored as bytes.
        text = self.because.token.decode("ascii")
        self.output.append("Token: {}".format(text))
        self.output.append("Succeeded in {}s".format(self.transfer.duration()))

        # Re-enable the button
        self.loginButton.setEnabled(True)

    def beSad(self):
        self.output.append("An error occurred, which is sad.")
        self.output.append("Failed in {}s".format(self.transfer.duration()))

        # Re-enable the button
        self.loginButton.setEnabled(True)