FLOSS Project Planets

Real Python: Modulo String Formatting in Python

Planet Python - Mon, 2022-01-24 09:00

If you’re writing modern Python code with Python 3, you’ll probably want to format your strings with Python f-strings. However, if you’re working with older Python codebases, you’re likely to encounter the string modulo operator for string formatting.

If you’re reading or writing Python 2 code, it’ll help if you’re familiar with this technique. Because the syntax still works in Python 3, you might even see developers use it in modern Python codebases.

In this tutorial, you’ll learn how to:

  • Use the modulo operator (%) for string formatting
  • Convert values into specific types before inserting them into your string
  • Specify the horizontal space a formatted value occupies
  • Fine-tune the display using conversion flags
  • Specify values using dictionary mapping instead of tuples

If you’re acquainted with the printf() family of functions of C, Perl, or Java, then you’ll see that these don’t exist in Python. However, there’s quite a bit of similarity between printf() and the string modulo operator, so if you’re familiar with printf(), then a lot of the following will feel familiar.

On the other hand, if you aren’t familiar with printf(), don’t worry! You don’t need any prior knowledge of printf() to master modulo string formatting in Python.

Free Bonus: Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Use the Modulo Operator for String Formatting in Python

You’ve probably used the modulo operator (%) before with numbers, in which case it computes the remainder from a division:

>>>>>> 11 % 3 2

With string operands, the modulo operator has an entirely different function: string formatting.

Note: These two operations aren’t very much alike. They only share the same name because they are represented by the same symbol (%).

Here’s what the syntax of the string modulo operator looks like:

<format_string> % <values>

On the left side of the % operator, <format_string> is a string containing one or more conversion specifiers. The <values> on the right side get inserted into <format_string> in place of the conversion specifiers. The resulting formatted string is the value of the expression.

Get started with an example where you call print() to display a formatted string using the string modulo operator:

>>>>>> print("%d %s cost $%.2f" % (6, "bananas", 1.74)) 6 bananas cost $1.74

In addition to representing the string modulo operation itself, the % character also denotes the beginning of a conversion specifier in the format string—in this case, there are three: %d, %s, and %.2f.

In the output, Python converted each item from the tuple of values to a string value and inserted it into the format string in place of the corresponding conversion specifier:

  • The first item in the tuple is 6, a numeric value that replaces %d in the format string.
  • The next item is the string value "bananas", which replaces %s.
  • The last item is the float value 1.74, which replaces %.2f.

The resulting string is 6 bananas cost $1.74, as demonstrated in the following diagram:

The String Modulo Operator

If there are multiple values to insert, then they must be enclosed in a tuple, as illustrated above. If there’s only one value, then you can write it by itself without the surrounding parentheses:

>>>>>> print("Hello, my name is %s." % "Graham") Hello, my name is Graham.

Notice also that string modulo operation isn’t only for printing. You can also format values and assign them to another string variable:

Read the full article at https://realpython.com/python-modulo-string-formatting/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Okular: Signing of unsigned signature fields has landed

Planet KDE - Mon, 2022-01-24 07:32

Up to today, Okular would kind of error out when opening a PDF file that contains a signature field that was unsigned (think like the old space in paper forms saying "sign here")


It would tell you "document is signed but can't be properly validated"




 

And that was it, you couldn't do much with the signature. When you tried to "see" it all the fields would be default like "Signed at 1 Jan 1970", etc.


With the new code we properly detect that there are unsigned signatures and we offer to sign them when interacting with it





Relevant merge requests:

https://invent.kde.org/graphics/okular/-/merge_requests/539

https://gitlab.freedesktop.org/poppler/poppler/-/merge_requests/1026

Categories: FLOSS Project Planets

Podcast.__init__: Improve Your Productivity By Investing In Developer Experience Design For Your Projects

Planet Python - Mon, 2022-01-24 06:30
When we are creating applications we spend a significant amount of effort on optimizing the experience of our end users to ensure that they are able to complete the tasks that the system is intended for. A similar effort that we should all consider is optimizing the developer experience for ourselves and other engineers who contribute to the projects that we work on. Adam Johnson recently wrote a book on how to improve the developer experience for Django projects and in this episode he shares some of the insights that he has gained through that project and his work with clients to help you improve the experience that you and your team have when collaborating on software development.Summary

When we are creating applications we spend a significant amount of effort on optimizing the experience of our end users to ensure that they are able to complete the tasks that the system is intended for. A similar effort that we should all consider is optimizing the developer experience for ourselves and other engineers who contribute to the projects that we work on. Adam Johnson recently wrote a book on how to improve the developer experience for Django projects and in this episode he shares some of the insights that he has gained through that project and his work with clients to help you improve the experience that you and your team have when collaborating on software development.

Announcements
  • Hello and welcome to Podcast.__init__, the podcast about Python’s role in data and science.
  • When you’re ready to launch your next app or want to try a project you hear about on the show, you’ll need somewhere to deploy it, so take a look at our friends over at Linode. With the launch of their managed Kubernetes platform it’s easy to get started with the next generation of deployment and scaling, powered by the battle tested Linode platform, including simple pricing, node balancers, 40Gbit networking, dedicated CPU and GPU instances, and worldwide data centers. Go to pythonpodcast.com/linode and get a $100 credit to try out a Kubernetes cluster of your own. And don’t forget to thank them for their continued support of this show!
  • Your host as usual is Tobias Macey and today I’m interviewing Adam Johnson about optimizing your developer experience
Interview
  • Introductions
  • How did you get introduced to Python?
  • Can you describe what you mean by the term "developer experience"?
    • How does it compare to the concept of user experience design?
  • What are the main goals that you aim for through improving DX?
  • When considering DX, what are the categories of focus for improvement? (e.g. the experience of a given software project, the developer’s physical environment, their editing environment, etc.)
  • What are some of the most high impact optimizations that a developer can make?
  • What are some of the areas of focus that have the most variable impact on a developer’s experience of a project?
  • What are some of the most helpful tools or practices that you rely on in your own projects?
  • How does the size of a development team or the scale of an organization impact the decisions and benefits around DX improvements?
  • One of the perennial challenges with selecting a given tool or architectural pattern is the continually changing landscape of software. How have your choices for DX strategies changed or evolved over the years?
  • What are the most interesting, innovative, or unexpected developer experience tweaks that you have encountered?
  • What are the most interesting, unexpected, or challenging lessons that you have learned while working on your book?
  • What are some of the potential pitfalls that individuals and teams need to guard against in their quest to improve developer experience for their projects?
  • What are some of the new tools or practices that you are considering incorporating into your own work?
Keep In Touch Picks
  • Tobias
  • Adam
    • Fan of Eternals, enjoyed Neil Gaiman series
    • Also general MCU fan, watched it all in lockdown
    • Moon Knight trailer
Closing Announcements
  • Thank you for listening! Don’t forget to check out our other show, the Data Engineering Podcast for the latest on modern data management.
  • Visit the site to subscribe to the show, sign up for the mailing list, and read the show notes.
  • If you’ve learned something or tried out a project from the show then tell us about it! Email hosts@podcastinit.com) with your story.
  • To help other people find the show please leave a review on iTunes and tell your friends and co-workers
Links

The intro and outro music is from Requiem for a Fish The Freak Fandango Orchestra / CC BY-SA

Categories: FLOSS Project Planets

Zato Blog: Remote API debugging with VS Code

Planet Python - Mon, 2022-01-24 04:31
  • Each Zato environment ships with default configuration that lets its servers be started from a Visual Studio Code’s debugger

  • Servers started in this way can run remotely, e.g. your local IDE may be on Mac or Windows while your Zato servers will be in a remote Linux instance. This will still let you debug your services deployed remotely.

  • It does not matter whether the server is under Docker or if it runs in a Linux VM directly

  • This article contains step-by-step instructions on how to start a Zato server in such a manner and how to debug your code remotely from VS Code

Prerequisites
  • Ensure that your remote Zato server runs in a Linux system that has at least 2 CPUs and 2 GB of RAM. If you use AWS, a medium instance will be the correct one to choose.

  • Make sure that there is SSH connectivity between your localhost and the remote Linux server, that is, you can ssh into the system where the Zato server is. As a reminder, if you use Docker Quickstart, the default port is 22022.

  • If the server runs in a Docker Quickstart instance, there are no further prerequisites and you can skip to the next section

  • If you created a Zato cluster yourself, check if these two files exist:

    /path/to/your/environment/.vscode/launch.json /path/to/your/environment/.vscode/settings.json
  • If the files do not exist, download them here: launch.json and settings.json

  • Once downloaded, save them to the locations above; if the .vscode directory does not exist, create it. The end result should be that if, for instance, your environment is in /opt/zato/env/dev, the files will go to /opt/zato/env/dev/.vscode.

SSH connections in VS Code
  • In VS Code, install an extension called Remote - SSH

  • After you install it, there will be a new button available in the bottom-left hand side corner of your IDE. The button will let you open SSH connections. Click it and then click “Connect to Host”

  • Choose the host where your Zato server is and the IDE will open a new window to connect to that host using SSH. Enter SSH credentials if necessary. Note that you will be in a new IDE window now.
Opening a remote environment
  • Once you are connected in a new window, choose “Open Folder”, select the directory where your environment is and click OK
  • Under Docker Quickstart, the path will be /opt/zato/env/qs-1/. In other environments, navigate to your environment’s path accordingly.
  • After opening the remote directory with a Zato environment, your IDE window will look like below:
Starting the server
  • Click the Run and Debug icon:
  • Click the play icon next to the Remote Zato Main option:
  • The IDE will work now on installing all of its own components in the remote Linux server - that may take a couple of minutes the first time around. The process is CPU-intensive which is why 2 CPUs are a prerequisite.

  • If VS Code tells you that its Python IDE extension is not installed in the remote SSH system, choose to install it over SSH. This may also take a couple of minutes.

  • Allow for some time until the IDE completes the installation of its remote components - there will be feedback provided in the IDE window’s footer. Once they are installed, proceed to the next section below.

Deploying a test service
  • Save the code below as demo.py and hot-deploy it in the now-already-started remote server. Note the highlighted line, we are going to add a breakpoint to it soon.
# -*- coding: utf-8 -*- # Zato from zato.server.service import Service class MyService(Service): def handle(self): msg = 'Hello, I am a demo service' self.logger.info(msg) Debugging a service
  • In the IDE, find the deployed service on a remote server under the path of /path/to/server/work/hot-deploy/current/demo.py and open it:
  • Add a breakpoint in line 9, as indicated below:
  • Invoke the service in any way you prefer, e.g. through REST, Dashboard or from command line

  • The debugger will stop at line 9, showing the local variables, the call stack and other details, exactly as if it was a local server


Congratulations! This concludes the process, everything is set up, you can debug your Zato API services remotely now.

Next steps
  • Start the tutorial to learn how to integrate APIs and build systems. After completing it, you will have a multi-protocol service representing a sample scenario often seen in banking systems with several applications cooperating to provide a single and consistent API to its callers.

  • Visit the support page if you need assistance.

  • Para aprender más sobre las integraciones de Zato y API en español, haga clic aquí

  • Pour en savoir plus sur les intégrations API avec Zato en français, cliquez ici

Categories: FLOSS Project Planets

IslandT: Starting a python language chess game project

Planet Python - Mon, 2022-01-24 02:41

Hello everyone, this is a new chess game project which I am going to start to create and update the code on this website weekly. In this first chapter of the project report, I am going to 1) render out the chessboard 2) write a code to recognize the square which I am touching on 3) Put a pawn on the board.

Without further due, let me start by explaining to you first what this project is all about and what is the final outcome of the project.

The reason I have started this project is that I want to create a chess game application that I can play with as a training exercise for myself to sharpen my chess skill. Stockfish is the chess engine that runs this application and the python code will use one of the Stockfish wrappers written in python to communicate with the Stockfish chess engine. Pygame will be used to create the chess game interface as well as to move pieces along the chessboard. The finished project will contain a common interface together with the chessboard and possibly also includes the AI and analysis part later on but not in this project.

The below python program will perform the above three goals, first, render the chessboard, then prints out the square on the command line and highlight the square area (I am using pycharm to write this program but you can certainly use another editor if you have one) each time the user pressed on one of the squares, and finally, put a pawn on one of the squares on the chessboard.

import sys, pygame import math pygame.init() size = width, height = 512, 512 white = 255, 178, 102 black = 126, 126, 126 hightlight = 192, 192, 192 title = "IslandT Chess" width = 64 # width of the square original_color = '' #empty chess dictionary chess_dict = {} #chess square list chess_square_list = [ "a8", "b8", "c8", "d8", "e8", "f8", "g8", "h8", "a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7", "a6", "b6", "c6", "d6", "e6", "f6", "g6", "h6", "a5", "b5", "c5", "d5", "e5", "f5", "g5", "h5", "a4", "b4", "c4", "d4", "e4", "f4", "g4", "h4", "a3", "b3", "c3", "d3", "e3", "f3", "g3", "h3", "a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2", "a1", "b1", "c1", "d1", "e1", "f1", "g1", "h1" ] # chess square position chess_square_position = [] #pawn image pawn0 = pygame.image.load("pawn.png") # create a list to map name of column and row for i in range(0, 8) : # control row for j in range(0, 8): # control column chess_square_position.append((j * width, i * width)) # create a dictionary to map the name of column and row for n in range(0, len(chess_square_position)): chess_dict[chess_square_list[n]] = chess_square_position[n] screen = pygame.display.set_mode(size) pygame.display.set_caption(title) rect_list = list() # this is the list of brown rectangle # used this loop to create a list of brown rectangles for i in range(0, 8): # control the row for j in range(0, 8): # control the column if i % 2 == 0: # which means it is an even row if j % 2 != 0: # which means it is an odd column rect_list.append(pygame.Rect(j * width, i * width, width, width)) else: if j % 2 == 0: # which means it is an even column rect_list.append(pygame.Rect(j * width, i * width, width, width)) # create main surface and fill the base color with light brown color chess_board_surface = pygame.Surface(size) chess_board_surface.fill(white) # next draws the dark brown rectangles on the chessboard surface for chess_rect in rect_list: pygame.draw.rect(chess_board_surface, black, chess_rect) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: pos = event.pos x = math.floor(pos[0] / width) y = math.floor(pos[1] / width) # print the square name which you have clicked on for key, value in chess_dict.items(): if (x * width, y * width) == (value[0],value[1]): print(key) original_color = chess_board_surface.get_at((x * width, y * width )) pygame.draw.rect(chess_board_surface, hightlight, pygame.Rect((x) * width, (y) * width, 64, 64)) elif event.type == pygame.MOUSEBUTTONUP: pos = event.pos x = math.floor(pos[0] / width) y = math.floor(pos[1] / width) pygame.draw.rect(chess_board_surface, original_color, pygame.Rect((x) * width, (y) * width, 64, 64)) # displayed the chess surface screen.blit(chess_board_surface, (0, 0)) screen.blit(pawn0, (0, 64)) # just testing... pygame.display.update()

The result is as follows…

pygame chess project

At the moment only one piece of pawn is on the chessboard and our next goal is to move that piece along the board which is going to happen in the next coming chapter!

If you are interested in another topic besides programming then do visit my blog and become my friend on Blogspot.

Categories: FLOSS Project Planets

Pages